Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Layout Management#

A tour of the standard layout managers and an introduction to custom layouts.

The Qt layout system provides a simple and powerful way of automatically arranging child widgets within a widget to ensure that they make good use of the available space.

Introduction#

Qt includes a set of layout management classes that are used to describe how widgets are laid out in an application’s user interface. These layouts automatically position and resize widgets when the amount of space available for them changes, ensuring that they are consistently arranged and that the user interface as a whole remains usable.

All QWidget subclasses can use layouts to manage their children. The setLayout() function applies a layout to a widget. When a layout is set on a widget in this way, it takes charge of the following tasks:

  • Positioning of child widgets

  • Sensible default sizes for windows

  • Sensible minimum sizes for windows

  • Resize handling

  • Automatic updates when contents change:

    • Font size, text or other contents of child widgets

    • Hiding or showing a child widget

    • Removal of child widgets

Qt’s Layout Classes#

Qt’s layout classes were designed for hand-written C++ code, allowing measurements to be specified in pixels for simplicity, so they are easy to understand and use. The code generated for forms created using Qt Designer also uses the layout classes. Qt Designer is useful to use when experimenting with the design of a form since it avoids the compile, link and run cycle usually involved in user interface development.

PySide6.QtWidgets.QGraphicsAnchorLayout

The QGraphicsAnchorLayout class provides a layout where one can anchor widgets together in Graphics View.

PySide6.QtWidgets.QGraphicsAnchor

The QGraphicsAnchor class represents an anchor between two items in a QGraphicsAnchorLayout.

PySide6.QtWidgets.QBoxLayout

The QBoxLayout class lines up child widgets horizontally or vertically.

PySide6.QtWidgets.QHBoxLayout

The QHBoxLayout class lines up widgets horizontally.

PySide6.QtWidgets.QVBoxLayout

The QVBoxLayout class lines up widgets vertically.

PySide6.QtWidgets.QFormLayout

The QFormLayout class manages forms of input widgets and their associated labels.

PySide6.QtWidgets.QGridLayout

The QGridLayout class lays out widgets in a grid.

PySide6.QtWidgets.QLayout

The QLayout class is the base class of geometry managers.

PySide6.QtWidgets.QLayoutItem

The QLayoutItem class provides an abstract item that a QLayout manipulates.

PySide6.QtWidgets.QSpacerItem

The QSpacerItem class provides blank space in a layout.

PySide6.QtWidgets.QWidgetItem

The QWidgetItem class is a layout item that represents a widget.

PySide6.QtWidgets.QSizePolicy

The QSizePolicy class is a layout attribute describing horizontal and vertical resizing policy.

PySide6.QtWidgets.QStackedLayout

The QStackedLayout class provides a stack of widgets where only one widget is visible at a time.

PySide6.QtWidgets.QButtonGroup

The QButtonGroup class provides a container to organize groups of button widgets.

PySide6.QtWidgets.QGroupBox

The QGroupBox widget provides a group box frame with a title.

PySide6.QtWidgets.QStackedWidget

The QStackedWidget class provides a stack of widgets where only one widget is visible at a time.

Horizontal, Vertical, Grid, and Form Layouts#

The easiest way to give your widgets a good layout is to use the built-in layout managers: QHBoxLayout , QVBoxLayout , QGridLayout , and QFormLayout . These classes inherit from QLayout , which in turn derives from QObject (not QWidget ). They take care of geometry management for a set of widgets. To create more complex layouts, you can nest layout managers inside each other.

  • A QHBoxLayout lays out widgets in a horizontal row, from left to right (or right to left for right-to-left languages).

    ../_images/qhboxlayout-with-5-children1.png
  • A QVBoxLayout lays out widgets in a vertical column, from top to bottom.

    ../_images/qvboxlayout-with-5-children1.png
  • A QGridLayout lays out widgets in a two-dimensional grid. Widgets can occupy multiple cells.

    ../_images/qgridlayout-with-5-children.png
  • A QFormLayout lays out widgets in a 2-column descriptive label- field style.

    ../_images/qformlayout-with-6-children.png

Laying Out Widgets in Code#

The following code creates a QHBoxLayout that manages the geometry of five QPushButtons , as shown on the first screenshot above:

window = QWidget()        button1 = QPushButton("One")        button2 = QPushButton("Two")
button3 = QPushButton("Three")
button4 = QPushButton("Four")
button5 = QPushButton("Five")
layout = QHBoxLayout(window)        layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
layout.addWidget(button4)
layout.addWidget(button5)        window.show()

The code for QVBoxLayout is identical, except the line where the layout is created. The code for QGridLayout is a bit different, because we need to specify the row and column position of the child widget:

window = QWidget()        button1 = QPushButton("One")        button2 = QPushButton("Two")
button3 = QPushButton("Three")
button4 = QPushButton("Four")
button5 = QPushButton("Five")
layout = QGridLayout(window)        layout.addWidget(button1, 0, 0)
layout.addWidget(button2, 0, 1)
layout.addWidget(button3, 1, 0, 1, 2)
layout.addWidget(button4, 2, 0)
layout.addWidget(button5, 2, 1)        window.show()

The third QPushButton spans 2 columns. This is possible by specifying 2 as the fifth argument to addWidget() .

QFormLayout will add two widgets on a row, commonly a QLabel and a QLineEdit to create forms. Adding a QLabel and a QLineEdit on the same row will set the QLineEdit as the QLabel ‘s buddy. The following code will use the QFormLayout to place three QPushButtons and a corresponding QLineEdit on a row.

window = QWidget()        button1 = QPushButton("One")
lineEdit1 = QLineEdit()        button2 = QPushButton("Two")
lineEdit2 = QLineEdit()
button3 = QPushButton("Three")
lineEdit3 = QLineEdit()
layout = QFormLayout(window)        layout.addRow(button1, lineEdit1)
layout.addRow(button2, lineEdit2)
layout.addRow(button3, lineEdit3)        window.show()

Tips for Using Layouts#

When you use a layout, you do not need to pass a parent when constructing the child widgets. The layout will automatically reparent the widgets (using setParent() ) so that they are children of the widget on which the layout is installed.

Note

Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.

You can nest layouts using addLayout() on a layout; the inner layout then becomes a child of the layout it is inserted into.

Adding Widgets to a Layout#

When you add widgets to a layout, the layout process works as follows:

  1. All the widgets will initially be allocated an amount of space in accordance with their sizePolicy() and sizeHint() .

  2. If any of the widgets have stretch factors set, with a value greater than zero, then they are allocated space in proportion to their stretch factor (explained below).

  3. If any of the widgets have stretch factors set to zero they will only get more space if no other widgets want the space. Of these, space is allocated to widgets with an Expanding size policy first.

  4. Any widgets that are allocated less space than their minimum size (or minimum size hint if no minimum size is specified) are allocated this minimum size they require. (Widgets don’t have to have a minimum size or minimum size hint in which case the stretch factor is their determining factor.)

  5. Any widgets that are allocated more space than their maximum size are allocated the maximum size space they require. (Widgets do not have to have a maximum size in which case the stretch factor is their determining factor.)

Stretch Factors#

Widgets are normally created without any stretch factor set. When they are laid out in a layout the widgets are given a share of space in accordance with their sizePolicy() or their minimum size hint whichever is the greater. Stretch factors are used to change how much space widgets are given in proportion to one another.

If we have three widgets laid out using a QHBoxLayout with no stretch factors set we will get a layout like this:

../_images/layout1.png

If we apply stretch factors to each widget, they will be laid out in proportion (but never less than their minimum size hint), e.g.

../_images/layout2.png

Custom Widgets in Layouts#

When you make your own widget class, you should also communicate its layout properties. If the widget uses one of Qt’s layouts, this is already taken care of. If the widget does not have any child widgets, or uses a manual layout, you can change the behavior of the widget using any or all of the following mechanisms:

  • Reimplement sizeHint() to return the preferred size of the widget.

  • Reimplement minimumSizeHint() to return the smallest size the widget can have.

  • Call setSizePolicy() to specify the space requirements of the widget.

Call updateGeometry() whenever the size hint, minimum size hint or size policy changes. This will cause a layout recalculation. Multiple consecutive calls to updateGeometry() will only cause one layout recalculation.

If the preferred height of your widget depends on its actual width (e.g., a label with automatic word-breaking), set the height-for-width flag in the widget’s size policy and reimplement heightForWidth() .

Even if you implement heightForWidth() , it is still a good idea to provide a reasonable sizeHint().

For further guidance when implementing these functions, see the Qt Quarterly article Trading Height for Width .

Layout Issues#

The use of rich text in a label widget can introduce some problems to the layout of its parent widget. Problems occur due to the way rich text is handled by Qt’s layout managers when the label is word wrapped.

In certain cases the parent layout is put into QLayout::FreeResize mode, meaning that it will not adapt the layout of its contents to fit inside small sized windows, or even prevent the user from making the window too small to be usable. This can be overcome by subclassing the problematic widgets, and implementing suitable sizeHint() and minimumSizeHint() functions.

In some cases, it is relevant when a layout is added to a widget. When you set the widget of a QDockWidget or a QScrollArea (with setWidget() and setWidget() ), the layout must already have been set on the widget. If not, the widget will not be visible.

Manual Layout#

If you are making a one-of-a-kind special layout, you can also make a custom widget as described above. Reimplement resizeEvent() to calculate the required distribution of sizes and call setGeometry() on each child.

The widget will get an event of type LayoutRequest when the layout needs to be recalculated. Reimplement event() to handle LayoutRequest events.

How to Write A Custom Layout Manager#

An alternative to manual layout is to write your own layout manager by subclassing QLayout . The Border Layout and Flow Layout examples show how to do this.

Here we present an example in detail. The CardLayout class is inspired by the Java layout manager of the same name. It lays out the items (widgets or nested layouts) on top of each other, each item offset by spacing() .

To write your own layout class, you must define the following:

  • A data structure to store the items handled by the layout. Each item is a QLayoutItem . We will use a QList in this example.

  • addItem() , how to add items to the layout.

  • setGeometry() , how to perform the layout.

  • sizeHint() , the preferred size of the layout.

  • itemAt() , how to iterate over the layout.

  • takeAt() , how to remove items from the layout.

In most cases, you will also implement minimumSize() .

The Header File ( `` card.h``

)#

#ifndef CARD_H
#define CARD_H
from PySide6 import QtWidgets

class CardLayout(QLayout):

# public
    CardLayout(int spacing): QLayout()
    { setSpacing(spacing); }
    CardLayout(int spacing, QWidget parent): QLayout(parent)
    { setSpacing(spacing); }
    ~CardLayout()
    def addItem(item):
    QSize sizeHint() override
    QSize minimumSize() override
    int count() override
    QLayoutItem itemAt(int) override
    QLayoutItem takeAt(int) override
    def setGeometry(rect):
# private
*> = QList<QLayoutItem()

#endif

The Implementation File ( `` card.cpp``

)#

##include "card.h"

First we define count() to fetch the number of items in the list.

def count(self):

    # QList::size() returns the number of QLayoutItems in m_items
    return m_items.size()

Then we define two functions that iterate over the layout: itemAt() and takeAt(). These functions are used internally by the layout system to handle deletion of widgets. They are also available for application programmers.

itemAt() returns the item at the given index. takeAt() removes the item at the given index, and returns it. In this case we use the list index as the layout index. In other cases where we have a more complex data structure, we may have to spend more effort defining a linear order for the items.

QLayoutItem CardLayout.itemAt(int idx)

    # QList::value() performs index checking, and returns nullptr if we are
    # outside the valid range
    return m_items.value(idx)

QLayoutItem CardLayout.takeAt(int idx)

    # QList::take does not do index checking
    return idx >= 0 and idx < m_items.size() if m_items.takeAt(idx) else 0

addItem() implements the default placement strategy for layout items. This function must be implemented. It is used by QLayout::add(), by the QLayout constructor that takes a layout as parent. If your layout has advanced placement options that require parameters, you must provide extra access functions such as the row and column spanning overloads of addItem() , addWidget() , and addLayout() .

def addItem(self, item):

    m_items.append(item)

The layout takes over responsibility of the items added. Since QLayoutItem does not inherit QObject , we must delete the items manually. In the destructor, we remove each item from the list using takeAt(), and then delete it.

CardLayout.~CardLayout()

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

The setGeometry() function actually performs the layout. The rectangle supplied as an argument does not include margin(). If relevant, use spacing() as the distance between items.

def setGeometry(self, r):

    QLayout.setGeometry(r)
    if m_items.size() == 0:
        return
    w = r.width() - (m_items.count() - 1) * spacing()
    h = r.height() - (m_items.count() - 1) * spacing()
    i = 0
    while i < m_items.size():
        o = m_items.at(i)
        geom = QRect(r.x() + i * spacing(), r.y() + i * spacing(), w, h)
        o.setGeometry(geom)
        i = i + 1

sizeHint() and minimumSize() are normally very similar in implementation. The sizes returned by both functions should include spacing(), but not margin().

def sizeHint(self):

    s = QSize(0, 0)
    n = m_items.count()
    if n > 0:
        s = QSize(100, 70) #start with a nice default size
    i = 0
    while i < n:
        o = m_items.at(i)
        s = s.expandedTo(o.sizeHint())
        i = i + 1

    return s + n * QSize(spacing(), spacing())

def minimumSize(self):

    s = QSize(0, 0)
    n = m_items.count()
    i = 0
    while i < n:
        o = m_items.at(i)
        s = s.expandedTo(o.minimumSize())
        i = i + 1

    return s + n * QSize(spacing(), spacing())

Further Notes#

  • This custom layout does not handle height for width.

  • We ignore isEmpty() ; this means that the layout will treat hidden widgets as visible.

  • For complex layouts, speed can be greatly increased by caching calculated values. In that case, implement invalidate() to mark the cached data is dirty.

  • Calling sizeHint() , etc. may be expensive. So, you should store the value in a local variable if you need it again later within in the same function.

  • You should not call setGeometry() twice on the same item in the same function. This call can be very expensive if the item has several child widgets, because the layout manager must do a complete layout every time. Instead, calculate the geometry and then set it. (This does not only apply to layouts, you should do the same if you implement your own resizeEvent(), for example.)

Layout Examples#

Many Qt Widgets examples already use layouts, however, several examples exist to showcase various layouts.

Address Book Tutorial

An introduction to GUI programming, showing how to put together a simple yet fully-functioning application.

Border-Layout-Example

Shows how to arrange child widgets along a border.

Calculator Example

The example shows how to use signals and slots to implement the functionality of a calculator widget, and how to use QGridLayout to place child widgets in a grid.

Calendar Widget Example

The Calendar Widget example shows use of QCalendarWidget.

Echo Plugin Example

This example shows how to create a Qt plugin.

Flow-Layout-Example

Shows how to arrange widgets for different window sizes.

Image Composition Example

Shows how composition modes work in QPainter.

Menus Example

The Menus example demonstrates how menus can be used in a main window application.

Simple Tree Model Example

The Simple Tree Model example shows how to use a hierarchical model with Qt’s standard view classes.