简体   繁体   English

Qt:调整QScrollArea的大小以最多显示4个小部件

[英]Qt: Resize QScrollArea to show 4 widgets at most

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. 我正在QScrollArea中动态添加和删除小部件,并且希望在滚动条出现之前同时显示最多四个小部件。 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, ... 因此,基本上,如果我有0-3个小部件并添加了另一个小部件,则调整滚动区域的大小以适应新的高度,然后,高度保持在4个小部件的大小,并且您必须滚动才能看到第5、6, ...

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). 问题在于sizeHint()并不总是正确的高度(有时太大),但size()也不总是正确(通常太小)。 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. 并非我的所有小部件都具有相同的高度,有时sizeHint似乎是正确的高度,有时是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. 我知道sizeHint是小部件想要的大小,而不是布局给它的大小,但是我不明白为什么大小不正确。

Any idea on how I should do it would be most appreciated. 我应该如何做的任何想法将不胜感激。

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). 而不是设置固定的高度,您应该重写sizeHint()以返回小部件想要的大小(这样,布局可以为其增加一些或更少一些,如果需要的话)。 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. 每当前四个子窗口小部件中的任何一个发生更改时,您都将要调用invalidate() ,以告知包含的布局应重新计算所有先前的缓存值。

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. 而且,如果您的小部件都在QVBoxLayout (我想,但是假设合理),那么您应该在计算中检索其间距和上边距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM