简体   繁体   中英

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

So far the only solution I have found is to subclass QItemDelegate and implement my alignment rule in the paint() function. Is it really the simplest way?

I am using the C++ API.

The alternative to subclussing QItemDelegate is to subclass your model and override data() method.

QVariant MyModel::data(const QModelIndex& index, int role) const {
    if (index.column() == yourCellIndex && role == Qt::TextAlignmentRole) {
        return Qt::AlignLeft;
    } else {
        return QVariant();
    }
}
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);

Following works for me:
http://doc.qt.io/qt-5/qstandarditem.html#setTextAlignment

void MainWindow::fillTable()
{
    sudukoItem->setText( "qq" );
    sudukoItem->setTextAlignment(Qt::AlignCenter);

    sudukoModel->appendRow( sudukoItem );
    sudukoTable->setModel( sudukoModel );

    sudukoTable->setRowHeight( ( sudukoModel->rowCount() - 1 ), 100 );
    sudukoTable->setColumnWidth( ( sudukoModel->columnCount() - 1 ), 100 );
}

where:

QTableView*         sudukoTable;
QStandardItemModel* sudukoModel;
QModelIndex*        modelIndex;

QStandardItem*      sudukoItem;

Credit goes to this comment: How to set text alignment on a column of QTableView programmatically?

`item->setTextAlignment(Qt::AlignCenter); work well for me. – Ratah

if you make a custom Model you can add this in YourModel::data()

if(role == Qt::TextAlignmentRole)
{
    if (col == 0 || col == 3) // change text alignment to horizontal and vertical center only for cells with in columns 0 and 3.
    return int(Qt::AlignHCenter | Qt::AlignVCenter);
}

source: https://doc.qt.io/qt-6/modelview.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM