I am dynamically adding and removing widgets in a QScrollArea, and I would like to show at most four widgets at the same time before the scroll bar appears. So basically, if I have 0-3 widgets and I add another one, the scroll area is resized to fit the new height, after that, the height stays at the 4 widgets size and you have to scroll to see the 5th, 6th, ...
Currently, I call the following method when a widget is inserted/removed.
void WidgetList::resizeScrollArea()
{
// height of the first four widgets
int widgetsHeight = 0;
for (int i = 0; i < _widgets.size() && i < 4; ++i)
{
// height of a widget
widgetsHeight += _widgets.at(i)->sizeHint().height();
}
// some leeway to make sure we have some gap between the widgets
_ui->scrollArea->setFixedHeight(widgetsHeight + 5);
}
The problem is that sizeHint() isn't always the correct height (sometimes too big), but neither is size() (often too small). So my scroll area is often a bit too big for the content, but sometimes it works.
Not all my widgets have the same height, and sometimes sizeHint seems to be the correct one, and sometimes it is size.
I understand sizeHint is the size the widget would like to have, not the one the layout gives it to it, but I don't get why size is incorrect.
Any idea on how I should do it would be most appreciated.