c++qtqt5qtablewidget

Calculating the exact needed height for a QTableWidget


I want to calculate the exact height a QTableWidget needs so that no vertical scroll bar is shown. What I do right now is for example:

tableWidget->setMaximumHeight(tableWidget->horizontalHeader()->height()
                              + tableWidget->rowHeight(0) * 4
                              + 4);

for this case, having 4 rows of the same height and KDE's Breeze style set, this works exactly:

Widget shown with KDE's Breeze style

But the additional 4 pixels seem to be style-dependent, using the Fusion style I get a bit more space than I need (cf. the last row, there are 2 unneeded white pixels):

Widget shown with the Fusion style

Is there a way to calculate the exact needed size independently of or better considering the style?

Update 2024-08: Using the solution below (looking at the viewport height) doesn't work anymore with all styles using Qt 6 / Plasma 6. I posted another question about that at Calculating the exact needed height for a QTableWidget (Qt 6 update)


Solution

  • The initial solution (messing with the viewport's height) does not reliably work for Qt 6 anymore.

    However, I found a solution which works for all combinations of Qt 5, Qt 6, Plasma 5, Plasma 6, the Fusion and the Breeze style. The frameWidth() does the trick:

    After the QTableWidget being added to a layout and show() or also only ensurePolished() is called (it does not work without), one can calculate the needed height using the widget->horizontalHeader()->height() plus the height of all rows (e.g. widget->rowCount() * widget->rowHeight(0) if all rows have the same height) plus 2 * widget->frameWidth().