Flow Layout Example

Flow Layout implements a layout that handles different window sizes. The widget placement changes depending on the width of the application window.

Screenshot of the Flow Layout example

The Flowlayout class mainly uses QLayout and QWidgetItem, while the Window uses QWidget and QLabel.

For more information, visit the Layout Management page.

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

FlowLayout Class Definition

The FlowLayout class inherits QLayout. It is a custom layout class that arranges its child widgets horizontally and vertically.

 
Sélectionnez
class FlowLayout : public QLayout
{
public:
    explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);
    explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);
    ~FlowLayout();

    void addItem(QLayoutItem *item) override;
    int horizontalSpacing() const;
    int verticalSpacing() const;
    Qt::Orientations expandingDirections() const override;
    bool hasHeightForWidth() const override;
    int heightForWidth(int) const override;
    int count() const override;
    QLayoutItem *itemAt(int index) const override;
    QSize minimumSize() const override;
    void setGeometry(const QRect &rect) override;
    QSize sizeHint() const override;
    QLayoutItem *takeAt(int index) override;

private:
    int doLayout(const QRect &rect, bool testOnly) const;
    int smartSpacing(QStyle::PixelMetric pm) const;

    QList<QLayoutItem *> itemList;
    int m_hSpace;
    int m_vSpace;
};

We reimplement functions inherited from QLayout. These functions add items to the layout and handle their orientation and geometry.

We also declare two private methods, doLayout() and smartSpacing(). doLayout() lays out the layout items, while the smartSpacing() function calculates the spacing between them.

FlowLayout Class Implementation

We start off by looking at the constructor:

 
Sélectionnez
FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing)
    : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing)
{
    setContentsMargins(margin, margin, margin, margin);
}

FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing)
    : m_hSpace(hSpacing), m_vSpace(vSpacing)
{
    setContentsMargins(margin, margin, margin, margin);
}

In the constructor we call setContentsMargins() to set the left, top, right and bottom margin. By default, QLayout uses values provided by the current style (see QStyle::PixelMetric).

 
Sélectionnez
FlowLayout::~FlowLayout()
{
    QLayoutItem *item;
    while ((item <