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.

+5


source to share


4 answers


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 on Qt::SizeHintRole

    using the method QTableView::setColumnWidth

    .
+6


source


You have a viewing problem and you are looking for the model part of your program.

The QTableView class has simple methods:

void QTableView::setColumnWidth(int column, int width)

      



and

void QTableView::setRowHeight(int row, int height)

      

+2


source


Add one or both lines for horizontal and / or vertical headings:

tableView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
tableView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);

      

0


source


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

      

enter image description here

0


source







All Articles