topic logo
Qt ⇢ Unit 7

Margin and Spacing

third layout unit

Summary

Shows how to change the spacing between and around layout items.

Background

Spacing and margin is used to visually organize elements in and between layouts.

The Layout3 Application

The sample application has a layout with two labels in it at startup. The layout has default margins and spacings. After a brief period it transitions twice to illustrate the meaning of margins and spacing in a layout.

Changing Margins and Spaces
Changing Margins and Spaces

The main window is again a QWidget derivative called “Layout3”. The header declares the constructor and two slots that are triggered after consecutive timeouts like in the last unit.

State 1: Default Values

Layout3.cpp - constructor
Layout3::Layout3()
{
    auto layout = new QVBoxLayout(this);
    for (int i = 0; i < 2; i++) {
        auto label = new QLabel("Layout Item");
        label->setMinimumSize(250, 50);
        layout->addWidget(label);
    }

    [..]
}

The constructor sets up a vertical layout and adds two labels to it.

label->setMinimumSize(250, 50);

“QWidget::setMinimumSize(w, h)” sets the minimum dimensions of a widget. Layouts won’t allow the widget to shrink bellow these size constraints.

There is subtle, but important difference to the previous examples: on initialization the application window is not resized. Instead a minimum size is set on the labels. The layout uses these attributes to size the items and the parent widget around it.

Previous sample applications allowed the user to make the application window smaller or wider than it’s initial size. This time around the user can only make it bigger than the minimum size.

The default margin for layouts is 9 pixel wide and the default spacing between items is 6 pixels apart. The lowest value is zero (no spacing/margin) while the highest value is much more than your display can handle.

State 2: Wide Spacing

layout()->setSpacing(30);

After the first timeout, the connected slot increases the spacing to 30 pixels using “QLayout::setSpacing(size)“. Visible on the above screenshot is, that the distance between the labels increases. The gray area between them is the application window shining through, as layouts are invisible and spacing/margins are transparent.

State 3: Wide Margins

layout()->setMargin(50);

Without much loitering around, the third state widens the margin using “QLabel::setMargin(size)“. This increases the bordering space around the widgets that are part of the layout.

Conclusion

This was a short unit regarding layouts and how they handle spacing of layout items. More on layouts in the next unit..