I have QTableView based on QAbstractTableModel. In QAbstractTableModel reimplemented method headerData() to set column name and width according to the model. But
switch( role )
{
...
case Qt::SizeHintRole : return QSize( 500, 0 );
...
}
has no effect. All columns in the table has the same width(). What I should to do to set initial column width properly.
P.S.: In this question was suggested to use delegates to solve the same issue, but I think headerData() should be used.
QAbstractItemModel
assumes that Qt::SizeHintRole
can be used in headerData
method to return supposed size of a header section. Hovewer, usage of this information depend on certain view implementation.
QHeaderView
uses Qt::SizeHintRole
to calculate its recommended width if it is horizontal and height if it is vertical.
QTableView
subscribes at signal sectionHandleDoubleClicked
of QHeaderView
and resizes appropriate column based on cells content size and width of header section. The width of header section is the width returned by headerData
with Qt::SizeHintRole
if this role is processed otherwise it's calculated based on header section text (content).
If you need to initialize column widths based on Qt::SizeHintRole
you need to:
QTableView
setModel
and use and set initial widths of columns based on Qt::SizeHintRole
using method QTableView::setColumnWidth
.After you've populated your model you can set individual policies on columns. This helped me where my table had 4 columns for which I wanted the first two to fill the view and the last two to fit the contents which was fairly narrow and while still having the view fully 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);
You have a view problem and your are seeking into the model part of your program.
QTableView class has simple methods:
void QTableView::setColumnWidth(int column, int width)
and
void QTableView::setRowHeight(int row, int height)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With