0

when i add a QLabel and QCheckBoxs to either a QVBoxLayout or a QHBoxLayout i would expect them to be evenly distributed but the checkboxes will allign tight at the very bottom (in the above example) and the label will be centered on the resulting free space in the widget. How can i change this behaviour to distribute all 3 widgets evenly?

Many thanks.

This is the example code:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    QLabel* l = new QLabel("Hi");
    QCheckBox* c = new QCheckBox("Label");
    QCheckBox* c2 = new QCheckBox("Label");
    l->setText("Hi");
    QVBoxLayout* v = new QVBoxLayout;

    v->addWidget(l);
    v->addWidget(c);
    v->addWidget(c2);
    setLayout(v);
    ui->setupUi(this);
}

And this is the result:

Result of Code Example

tobilocker
  • 891
  • 8
  • 27
  • Have you tried playing with `addStretch()`, `addStrut()` and `addSpacing()` after adding the widgets to the layout? I'd suggest you to try `QGridLayout` too. – dschulz Sep 22 '16 at 15:00

1 Answers1

1

Take a look at QSizePolicy. You need to setSizePolicy for your QLabel and QCheckBoxes to be QSizePolicy::Preferred, from the docs:

The default policy is Preferred/Preferred, which means that the widget can be freely resized, but prefers to be the size sizeHint() returns. Button-like widgets set the size policy to specify that they may stretch horizontally, but are fixed vertically. The same applies to lineedit controls (such as QLineEdit, QSpinBox or an editable QComboBox) and other horizontally orientated widgets (such as QProgressBar).

Currently, your QLabel has preferred height, while both of the QCheckBoxes has fixed height. That means that the QLabel will be expanded automatically to take up any additional vertical space (that can't be taken by the QCheckBoxes.

So, In order to set all your widgets to Preferred height, you need to add the following to your constructor:

l->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
c->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
c2->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

Another option, would be to add spacers around each one of the widgets, like this:

v->addStretch();
v->addWidget(l);
v->addStretch();
v->addWidget(c);
v->addStretch();
v->addWidget(c2);
v->addStretch();
setLayout(v);

This way QSpacerItems will take up all the additional space.

Mike
  • 8,055
  • 1
  • 30
  • 44