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

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

Try these:

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

Try this:

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