Flow Layout Example

Shows how to arrange widgets for different window sizes.

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

../_images/flowlayout-example.png

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.

class FlowLayout(QLayout):

# public
    FlowLayout = explicit(QWidget parent, int margin = -1, int hSpacing = -1, int vSpacing = -1)
    FlowLayout = explicit(int margin = -1, int hSpacing = -1, int vSpacing = -1)
    ~FlowLayout()
    def addItem(item):
    horizontalSpacing = int()
    verticalSpacing = int()
    Qt.Orientations expandingDirections() override
    hasHeightForWidth = bool()
    heightForWidth = int(int)
    count = int()
    itemAt = QLayoutItem(int index)
    minimumSize = QSize()
    def setGeometry(rect):
    sizeHint = QSize()
    takeAt = QLayoutItem(int index)
# private
    doLayout = int(QRect rect, bool testOnly)
    smartSpacing = int(QStyle.PixelMetric pm)
*> = QList<QLayoutItem()
    m_hSpace = int()
    m_vSpace = int()

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:

def __init__(self, parent, margin, hSpacing, vSpacing):
    QLayout.__init__(self, parent)
    self.m_hSpace = hSpacing
    self.m_vSpace = vSpacing

    setContentsMargins(margin, margin, margin, margin)

def __init__(self, margin, hSpacing, vSpacing):
    self.m_hSpace = hSpacing
    self.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 PixelMetric ).

FlowLayout::~FlowLayout()

    item = QLayoutItem()
    while ((item = takeAt(0)))
        del item

In this example we reimplement addItem(), which is a pure virtual function. When using addItem() the ownership of the layout items is transferred to the layout, and it is therefore the layout’s responsibility to delete them.

def addItem(self, item):

    itemList.append(item)

addItem() is implemented to add items to the layout.

def horizontalSpacing(self):

    if (m_hSpace >= 0) {
        return m_hSpace
    else:
        def smartSpacing(QStyle.PM_LayoutHorizontalSpacing):


def verticalSpacing(self):

    if (m_vSpace >= 0) {
        return m_vSpace
    else:
        def smartSpacing(QStyle.PM_LayoutVerticalSpacing):

We implement horizontalSpacing() and verticalSpacing() to get hold of the spacing between the widgets inside the layout. If the value is less than or equal to 0, this value will be used. If not, smartSpacing() will be called to calculate the spacing.

def count(self):

    return itemList.size()

FlowLayout::itemAt = QLayoutItem(int index)

    return itemList.value(index)

FlowLayout::takeAt = QLayoutItem(int index)

    if (index >= 0 and index < itemList.size())
        return itemList.takeAt(index)
    return None

We then implement count() to return the number of items in the layout. To navigate the list of items we use itemAt() and takeAt() to remove and return items from the list. If an item is removed, the remaining items will be renumbered. All three functions are pure virtual functions from QLayout .

Qt.Orientations FlowLayout.expandingDirections()

    return { }

expandingDirections() returns the Orientation s in which the layout can make use of more space than its sizeHint().

def hasHeightForWidth(self):

    return True

def heightForWidth(self, int width):

    height = doLayout(QRect(0, 0, width, 0), True)
    return height

To adjust to widgets of which height is dependent on width, we implement heightForWidth(). The function hasHeightForWidth() is used to test for this dependency, and heightForWidth() passes the width on to doLayout() which in turn uses the width as an argument for the layout rect, i.e., the bounds in which the items are laid out. This rect does not include the layout margin().

def setGeometry(self, rect):

    QLayout.setGeometry(rect)
    doLayout(rect, False)

def sizeHint(self):

    def minimumSize():

def minimumSize(self):

    size = QSize()
    for item in qAsConst(itemList):
        size = size.expandedTo(item.minimumSize())
    margins = contentsMargins()
    size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom())
    return size

setGeometry() is normally used to do the actual layout, i.e., calculate the geometry of the layout’s items. In this example, it calls doLayout() and passes the layout rect.

sizeHint() returns the preferred size of the layout and minimumSize() returns the minimum size of the layout.

def doLayout(self, QRect rect, bool testOnly):

    left, = int()
    getContentsMargins(left, top, right, bottom)
    effectiveRect = rect.adjusted(+left, +top, -right, -bottom)
    x = effectiveRect.x()
    y = effectiveRect.y()
    lineHeight = 0

doLayout() handles the layout if horizontalSpacing() or verticalSpacing() don’t return the default value. It uses getContentsMargins() to calculate the area available to the layout items.

for item in qAsConst(itemList):
    wid = item.widget()
    spaceX = horizontalSpacing()
    if (spaceX == -1)
        spaceX = wid.style().layoutSpacing(
            QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
    spaceY = verticalSpacing()
    if (spaceY == -1)
        spaceY = wid.style().layoutSpacing(
            QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)

It then sets the proper amount of spacing for each widget in the layout, based on the current style.

    nextX = x + item.sizeHint().width() + spaceX
    if (nextX - spaceX > effectiveRect.right() and lineHeight > 0) {
        x = effectiveRect.x()
        y = y + lineHeight + spaceY
        nextX = x + item.sizeHint().width() + spaceX
        lineHeight = 0

    if (not testOnly)
        item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
    x = nextX
    lineHeight = qMax(lineHeight, item.sizeHint().height())

return y + lineHeight - rect.y() + bottom

The position of each item in the layout is then calculated by adding the items width and the line height to the initial x and y coordinates. This in turn lets us find out whether the next item will fit on the current line or if it must be moved down to the next. We also find the height of the current line based on the widgets height.

FlowLayout.smartSpacing = int(QStyle.PixelMetric pm)

    parent = self.parent()
    if (not parent) {
        return -1
    } else if (parent.isWidgetType()) {
        pw = QWidget (parent)
        return pw.style().pixelMetric(pm, None, pw)
    else:
        return QLayout (parent).spacing()

smartSpacing() is designed to get the default spacing for either the top-level layouts or the sublayouts. The default spacing for top-level layouts, when the parent is a QWidget , will be determined by querying the style. The default spacing for sublayouts, when the parent is a QLayout , will be determined by querying the spacing of the parent layout.

Example project @ code.qt.io