How to get right row height in Qt for QTableView object?

10,977

Solution 1

Try these:

verticalHeader()->setDefaultSectionSize(int size)
horizontalHeader()->setDefaultSectionSize(int size)

Solution 2

Try this:

void QHeaderView::setResizeMode(QHeaderView::ResizeToContents);

Solution 3

There seems to be a bug in Qt when you call resizeRowsToContents on the tableView of an empty table with a hidden verticalHeader, it does not accurately resize the rows. And considering that tables often start empty, this is a troublesome problem indeed. Fortunately I found a workaround on a qtcentre thread, as follows:

If table/model is not empty, use:

        tableView->resizeRowsToContents();
        const int rowHeight = tableView->verticalHeader()->sectionSize(0);
        tableView->verticalHeader()->setDefaultSectionSize(rowHeight);

Otherwise, here is a workaround:

        // workaround for Qt empty table auto-row-sizing problem
        const int rowHeight = tableView->verticalHeader()->minimumSectionSize();
        tableView->verticalHeader()->setDefaultSectionSize(rowHeight);

Solution 4

I'm using Qt 4.7 and this worked for me on QTableView:

tableView->resizeColumnsToContents();
tableView->resizeRowsToContents();
tableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
Share:
10,977
DragonionS
Author by

DragonionS

Updated on July 24, 2022

Comments

  • DragonionS
    DragonionS almost 2 years

    From this screenshot you can see a lot of space inside the rows:

    alt text

    I've used these functions to get resizing:

    resizeRowsToContents();
    resizeColumnsToContents();
    

    How can I get a better fit for cells/rows sizes?

  • Remy Blank
    Remy Blank over 13 years
    That works well for columns, but doesn't seem to work with rows.
  • mike rodent
    mike rodent over 3 years
    Hmmm... this seems to set every row to the same height.
  • mike rodent
    mike rodent over 3 years
    For me this does appear to work for rows... hmmm (PyQt5)
  • Patrick Parker
    Patrick Parker over 3 years
    @mikerodent for an empty table, yes it does. in my case I wanted all the rows to be the same height though, so it was fine.
  • mike rodent
    mike rodent over 3 years
    My tables aren't empty and the rows are different heights. In my system this imposes the same height for each row. There is therefore no point in calling resizeRowsToContents before setDefaultSectionSize.
  • Patrick Parker
    Patrick Parker over 3 years
    @mikerodent yes, there is an effect. resizeRowsToContents affects the existing rows with contents. if you allow word wrap for example, some could end up double height. setDefaultSectionSize affects the future rows which have not yet been inserted.