SPlatten
SPlatten

Reputation: 5760

QVBoxLayout how to add spacer row

Is it possible to add a spacing row to a QVBoxLayout? I tried using a QPushButton and then hiding, but this doesn't work.

I want the layout to contain 5 buttons with a spacing row between buttons 4 and 5.

Upvotes: 0

Views: 6246

Answers (2)

Dimitry Ernot
Dimitry Ernot

Reputation: 6594

You don't need to handle the QSpacerItem yourself (the documentation lists the methods you should use instrad of creating the QSpacerItem).

If you want to add a space with a specific size, you can use QVBoxLayout::addSpacing():

    QWidget* w = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(w);
    layout->addWidget(new QPushButton("first"));
    layout->addWidget(new QPushButton("second"));
    layout->addWidget(new QPushButton("third"));
    layout->addWidget(new QPushButton("fourth"));
    layout->addSpacing(50);
    layout->addWidget(new QPushButton("fifth"));
    w->show();

It will be a minimum space of 50 pixel between fourth and fifth:

enter image description here enter image description here

If you want to put the button fifth at the bottom and keep the others at the top, use QVBoxLayout::addStretch():

    QWidget* w = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(w);
    layout->addWidget(new QPushButton("first"));
    layout->addWidget(new QPushButton("second"));
    layout->addWidget(new QPushButton("third"));
    layout->addWidget(new QPushButton("fourth"));
    layout->addStretch(1);
    layout->addWidget(new QPushButton("fifth"));
    w->show();

enter image description here enter image description here

Upvotes: 2

arsdever
arsdever

Reputation: 1262

Try adding QSpacerItem.

QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(new QPushButton("first"));
layout->addWidget(new QPushButton("second"));
layout->addWidget(new QPushButton("third"));
layout->addWidget(new QPushButton("fourth"));
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding));
layout->addWidget(new QPushButton("fifth"));

Upvotes: 0

Related Questions