Initial column width in QTableView through model
I have a QTableView based on QAbstractTableModel. QAbstractTableModel reimplements the headerData () method to set the column name and width to match the model. But
switch( role )
{
...
case Qt::SizeHintRole : return QSize( 500, 0 );
...
}
does not affect. All columns in the table have the same width (). What do I need to do to set the initial column width correctly.
PS: This suggested using delegates to solve the same problem, but I think headerData () should be used.
source to share
QAbstractItemModel
suggests it Qt::SizeHintRole
can be used in the method headerData
to return the estimated size of the header section. Hovewer, the use of this information is implementation specific.
QHeaderView
uses Qt::SizeHintRole
to calculate the recommended width if horizontal and height if vertical.
QTableView
subscribes to the signal sectionHandleDoubleClicked
QHeaderView
and resizes the corresponding column based on the size of the content content and the width of the header section. The header section width is the width returned headerData
by Qt::SizeHintRole
, if this role is handled otherwise, it is calculated based on the text (content) of the header section.
If you need to initialize column widths based on Qt::SizeHintRole
, you need:
- inherits your class from
QTableView
- reimplement method
setModel
and use and set the initial column widths based onQt::SizeHintRole
using the methodQTableView::setColumnWidth
.
source to share
After populating your model, you can set individual policies in the columns. This helped me where I had 4 columns in my table for which I wanted the first two to fill the view and the last two to match the content, which was quite narrow and still completely filled.
this->ui->tableView->setModel(model);
ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->tableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
source to share