Important: Please read the Qt Code of Conduct -

Spacing in vertical layout

  • Hi
    I have a scrollable area containing a Vertical layout.
    I add items to the vertical layout but there appears to be a large amount of spacing between them as shown here

    How can I get rid of this?

    Here is the code for my main window

    for (int s = 0; s < 3; s++)
    QSplineSeries* series = new QSplineSeries();

    for (int i = 0; i < 100; ++i)
    QChart* chart = new QChart();

    QChartView* chartView = new QChartView(chart);

    QHBoxLayout* hoizontalLayout = new QHBoxLayout(this);
    QLabel *l1 = new QLabel(QString("%1").arg(s));


    QLabel *l2 = new QLabel(QString("geo %1").arg(s));



  • Vertical and horizontal layouts always "spread" widgets evenly. If parent widget is 300px and you have 3 children widgets, all of them will end up with 100px. To "compact" just add horizontal or vertical spacer as last in layout. For vertical layout add vertical spacer, and for horizontal add horizontal spacer.

  • Thanks for your reply
    I added this code to the end of the for loop -
    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);


    But the result is still the same?

  • Lifetime Qt Champion

    If i'm not wrong, a simple addStretch(1) after your last widget should push them to the top.

  • I have tried both of these but the result is still the same

    // spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    // ui.verticalLayout->addItem(spacer);
    Is there anything else I can try?

  • What is the minimum size of those widgets? Also, you can try to play with layout->setSpacing(), or try to set spacing directly in layout properties from the designer.

  • Well the spacer item should've worked if you would have set the vertical sizepolicy to expanding. AFAIK the QSpacerItem consists of: width, height, hData(which is horizontal data), and vData(which is vertical data). So you should have for the spacer item this:

    @spacer = new QSpacerItem(40, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);@

    Also you should use addSpacerItem instead of addItem.

Log in to reply