QStyledItemDelegate method sizeHint did not call QTableView row
I have a QTableView using QSqlQueryModel (it fetches data from SQLite).
The QStyledItemDelegate subclass is named MiniItemDelegate
, which I use as a delegate for the items. I created a sizeHint () method :
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 am not sure why this method is not being 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();
And it doesn't:
QHeaderView* headerView = ui->PList_tableView->horizontalHeader(); headerView->setResizeMode(QHeaderView::ResizeToContents);
source to share
QStyledItemDelegate :: sizeHint is only useful when QTableView :: resizeRowsToContents, QTableView :: resizeRowToContents, QTableView :: resizeColumnsToContents, and QTableView :: resizeColumnToContents are called. or use
QHeaderView* headerView = tableView->horizontalHeader(); headerView->setResizeMode(QHeaderView::ResizeToContents);
source to share
(The loan at which the loan should be provided). In @ HostileFork 's comment on the Qt Forum Discussion , there is a thread of comments. Inside this thread, user mikhailt offers a good solution .
VerticalHeader has a DefaultSectionSize property that you can customize. It doesn't matter if the vertical header (labels on the left side of the table) is 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 the height of each data row separately or resizing the table.
Depending on the age of the comment thread where I found it, this already worked in Qt 4.
source to share