How to set text alignment on a column of QTableView programmatically ?

How to set text alignment on a column of QTableView programmatically ?

Asked on January 8, 2019 in Qt.
Add Comment


  • 2 Answer(s)

    Text alignment on a column of QTableView:

    The  subclussing QItemDelegate is  used by the subclass  model and override data().

    QVariant MyModel::data(const QModelIndex& index, int role) const {
        if (index.column() == yourCellIndex && role == Qt::TextAlignmentRole) {
            return Qt::AlignLeft;
        } else {
            return QAbstractTableModel::data(index, role);
        }
    }
    
    Answered on January 8, 2019.
    Add Comment

    The simple way of easiest code is:

    QSqlTableModel *model2= new QSqlTableModel();
     
    model2->setTable("Save");
    model2->select();
     
    QSortFilterProxyModel *proxy1=new QSortFilterProxyModel();
    proxy1->setSourceModel(model2);
     
    QStandardItemModel *modd=new QStandardItemModel();
     
    for (int z =0; z< proxy1->rowCount(); ++z)
        {
        for (int y =0; y< proxy1->columnCount(); ++y)
            {
            QStandardItem *item= new QStandardItem();
             item->setText(proxy1->index(z,y).data().toString());
             item->setTextAlignment(Qt::AlignCenter);
             modd->setItem(z,y,item);
             }
    }
    ui->tableView->setModel(modd);
    

     

    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.