Resize a QWidget containing a QVBoxLayout in runti

2019-08-11 09:18发布

问题:

In this application, a list of HBoxLayouts is generated and put into a VBoxLayout in order to form a dynamically filled list of commands. There is a button above each sub-list which has the capability to hide the controls below it. The problem: when a sub-list is hidden, the widget which contains the broadest VBoxLayout does not change in size! The VBoxLayout then stretches to compensate. I want the container widget to shrink when it contains fewer items! It looks like this:

The problem is, when I hide a list under one of the PushButtons, the containing widget won't shrink! the VBoxLayout just expands when there are less visible items :(

Here is a picture of how I see my little GUI.

Here is some code from the broader layout setup:

scrollArea = new QScrollArea(this);
scrollAreaLayoutWidget = new QWidget(scrollArea);
scrollAreaLayout = new QVBoxLayout(scrollAreaLayoutWidget);
//scrollAreaLayout is filled with all the stuff you see inside the scroll area...
scrollArea->setWidget(scrollAreaLayoutWidget);

I have tried changing the QSizePolicy of the container widget (blue box) in a number of ways. I've found dozens of resizing questions but I have somehow not discovered an answer. Is there a magic auto-resize setting that I'm missing? Let me know if this is painfully vague or incomplete. Any comment is welcome!

回答1:

Turns out all I had to do was create a custom SLOT for when the button that hides part of the Ui is clicked and hide the relevant widget within that function. In the same function, I called [containerWidget]->adjustSize(); and it did exactly what I was looking for.