Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial width of column in QTableView via model

Tags:

qt

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.

like image 548
kaa Avatar asked Sep 24 '14 07:09

kaa


3 Answers

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:

  • inherit your class from QTableView
  • reimplement method setModel and use and set initial widths of columns based on Qt::SizeHintRole using method QTableView::setColumnWidth.
like image 144
Ezee Avatar answered Oct 22 '22 16:10

Ezee


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);

enter image description here

like image 32
partyd Avatar answered Oct 22 '22 16:10

partyd


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)
like image 3
Martin Avatar answered Oct 22 '22 15:10

Martin