I have a QVBoxLayout in which I add dynamically on runtime other QWidget s:
for(int i = 0; i < value; i++)
{
QList<QWidget*> widgetList_i;
//... widgetList_i.append(a lot of widgets)
ui->verticalLayout->addWidget(widget_i);
}
There is a lot of wasted space between those added widgets:
When I run the application, I can compress the height, with the mouse.
Limiting each widgetList_i
widget height using setMaximumheigth()
is a nice approach, but then I have spaces wasted in the beginning and end:
Adding just a ui->vertivalLayout->addStretch(1);
causes empty space at the end. The beginning of that layout is nice:
Adding a QSpacerItem makes it worse:
Isn't there a function which sets the layout's height regarding the added widgets to a minimum?
Quick answer
Before your insertion code, put this line:
ui->verticalLayout->parentWidget()->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Maximum);
Also, you can find this property in Qt Designer, be sure that you are selecting the layout and not the QDockWidget.
Explanation
Layouts do not have sizes but Widgets. Layout are inside other widgets, so you need to change the size of the parent widget of your layout. setSizePolicy
changes the size behavior of a widget. This method has 2 arguments: horizontal policy and vertical policy. You may keep horizontal as Preferred
, that is the default and change the vertical policy to Maximum
, that means that the preferred policy of the widget is the max size.