2
votes

I have a QVBoxLayout in wich 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: With wasted space between dynamic QWidegts

When I run the application, I can compress the heigth, with the mouse.

Compressed the space with dragging the border with the mouse

Limiting each widgetList_i Widget heigth by setMaximumheigth() is a nice approach, but then I have spaces wasten in the beginning and end: MaximumHeigth

Adding just a ui->vertivalLayout->addStretch(1); causes empty space at the end. The beginning of that layout is nice: enter image description here

Main question: Isn't there a function which sets the layouts heigth regarding the added widgets to a minimum?
Side question: How can I add a vertical scrollbar to that widget ?

EDIT: - Adding a spaceritem make it worse: SpaceItem and does not solve my problem

1

1 Answers

4
votes

Quick answer

Before your insertion code put this line

ui->verticalLayout->parentWidget()->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Maximum);

*also you can find this properties in QtDesigner, 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 have 2 arguments: horizontal policy and vertical policy. You may keep horizontal as Preferred that is the default nad change the vertical policy to Maximum that means that the preferred policy of the widget is the max size.

Side question: QScrollArea provide you scroll capabilities to widgets. You can wrap your QLayout in a QWidget, and then in a QScrollArea.