3

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

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103

1 Answers1

5

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.

Edwin Rodríguez
  • 1,229
  • 10
  • 19
  • As in the screenshot appended above, a SpaceItem dow not work for me. – Ralf Wickum Nov 09 '15 at 16:04
  • @RalfWickum I update the answer. Tell me if it works – Edwin Rodríguez Nov 09 '15 at 19:18
  • Yes that organized my Widgets very well. But that also enabled another problem: Now, I can not resize between those DockWidgets, means I can not drag and move the border of the upper dockwidget and the lower one? – Ralf Wickum Nov 10 '15 at 09:05
  • @RalfWickum I recommend you to put add an spacer to the lower Dock and set a MinimumExpanding policy to the upper Dock instead of set to Maximum policy the lower one. Maybe you can add to the original question the details about DockWidgets and desired behavior at start, moving the splitter, poping out the docks, etc. – Edwin Rodríguez Nov 10 '15 at 13:33