Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QLayout with minimum space required

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:

With wasted space between dynamic QWidegts

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

Compressed the space with dragging the border 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:

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

Adding a QSpacerItem makes it worse:

SpaceItem

Isn't there a function which sets the layout's height regarding the added widgets to a minimum?

like image 863
Ralf Wickum Avatar asked Sep 05 '26 10:09

Ralf Wickum


1 Answers

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.

like image 174
Edwin Rodríguez Avatar answered Sep 09 '26 03:09

Edwin Rodríguez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!