Adjust QTableView height according to contents

Sometimes we need to show all contents and get rid of that scrollbar

In my layout, my dynamically generated QTableViews seem to get resized to only show one row. I want to have the container of the table views to have a scrollbar instead of the individual table views, which should show full contents.

Qt doesn’t have anything built in for this apparently, you need to calculate and set the size manually.

This is how I’m doing it for vertical sizing (Qt 5.8). You might want to add setMaximumHeight/width.

To develop it further, it should check for presence of a horizontal scrollbar before adding that to the size. This suffices for my usage though.

void verticalResizeTableViewToContents(QTableView *tableView)
{
    int count=tableView->verticalHeader()->count();
    int scrollBarHeight=tableView->horizontalScrollBar()->height();
    int horizontalHeaderHeight=tableView->horizontalHeader()->height();
    int rowTotalHeight=0;
    for (int i = 0; i < count; ++i) {
        rowTotalHeight+=tableView->verticalHeader()->sectionSize(i);
    }
    tableView->setMinimumHeight(horizontalHeaderHeight+rowTotalHeight+scrollBarHeight);
}

Originally a StackOverflow post

Other Qt things of mine on GitHub

Hey! What did you think?