I have QTableView using a QSqlQueryModel (it fetches data from SQLite).

There is a QStyledItemDelegate subclass called MiniItemDelegate that I use as a delegate for the items. I set up a sizeHint() method like this:

QSize MiniItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                                 const QModelIndex &index) const
{
    // just for testing...breakpoint shows this line never gets called
    return QSize(256,256);  
}

I'm not sure why this method isn't called when I run the following code:

m_pMiniItemDelegate = new MiniItemDelegate(this);
ui->PList_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->PList_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->PList_tableView->setItemDelegate(m_pMiniItemDelegate);
ui->PList_tableView->setAlternatingRowColors(true);
ui->PList_tableView->setModel(ListMiniSqlModel::instance());

This also doesn't work:

ui->PList_tableView->resizeColumnsToContents();
ui->PList_tableView->resizeRowsToContents();

Nor does this:

QHeaderView* headerView = ui->PList_tableView->horizontalHeader();
headerView->setResizeMode(QHeaderView::ResizeToContents);
有帮助吗?

解决方案

QStyledItemDelegate::sizeHint is useful only when QTableView::resizeRowsToContents, QTableView::resizeRowToContents, QTableView::resizeColumnsToContents and QTableView::resizeColumnToContents are called. or use

QHeaderView* headerView = tableView->horizontalHeader();
headerView->setResizeMode(QHeaderView::ResizeToContents);

其他提示

Have you tried: setColumnWidth or setRowHeight and horizontalHeader()->setResizeMode(QHeaderView::Fixed) ?

(Credit where credit is due.) In @HostileFork's comment about a Qt Forum discussion, there's a comment thread. Within that thread, a user mikhailt offers a good solution.

The verticalHeader has a DefaultSectionSize property that can be adjusted. It doesn't matter whether the vertical header (labels on the left side of the table) is actually being displayed or not, the size will still be used.

ui->PList_tableView->verticalHeader()->setDefaultSectionSize(34);

This just solved my problem with Qt 5.6, and saved me from adjusting each data row's height separately, or causing a resize on a table.

Based on the age of the comment thread where I found it, this was already working in Qt 4, too.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top