0
votes

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.

1

1 Answers

0
votes

Instead of setting fixed height, you should override sizeHint() to return the size your widget would like to be (so that a layout could give it some extra, or a bit less, if it needs to). You will want to call invalidate() whenever any of those first 4 child widgets are changed, to tell the containing layout that any previous cached values should be recomputed.

And if your widgets are all in a QVBoxLayout (I'm guessing, but seems reasonable to assume), then you should be retrieving its spacing and top margin in your computation.