9.6.1.  Spacing, Stretching, and Struts

[ fromfile: layout.xml id: spacers ]

Without using Designer, you can use the API of QLayout directly to specify spacers, stretches, and struts between widgets. Box layouts, for example, offer the following functions:

Revisiting Example 9.7, you can see how to make the layout behave a little better during resizing. Figure 9.13 shows the results of adding some stretch and some spacing to this application.

Figure 9.13. Improved Layout with Stretch and Spacing

Improved Layout with Stretch and Spacing

Normally, layouts try to treat all widgets equally. When you want one widget to be off to a side, or pushed away from another, you can use stretches and spacing to deviate from that norm. Example 9.9 demonstrates how to use stretches and spacing.

Example 9.9. src/layouts/stretch/cardtable.cpp

[ . . . . ]
    row = new QHBoxLayout();
    row->addWidget(new Card("td"));
    row->addWidget(new Card("js"));
    row->addWidget(new Card("kc"));
    rows->addLayout(row);
    rows->addStretch(1);                    1
    QVBoxLayout* buttons = new QVBoxLayout();
    buttons->addStretch(1);                 2
    buttons->addWidget(new QPushButton("Deal"));
    buttons->addWidget(new QPushButton("Shuffle"));
    buttons->addSpacing(20);                3
    QHBoxLayout* cols = new QHBoxLayout();
    setLayout(cols);
    cols->addLayout(rows);
    cols->addLayout(buttons);
    cols->addStretch(0);                    4
}
[ . . . . ]

1

Stretchable space for rows.

2

Stretchable space before buttons in column.

3

Fixed spacing after buttons.

4

How does this affect the size of the buttons?


If you build and run this application using Example 9.9 instead of Example 9.7, you can resize the main window and observe that the buttons no longer grow, and are pushed off to the corner. The horizontal spacing between the cards does not grow, but the vertical spacing does.