1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
5 \title Layout Management
6 \ingroup qt-basic-concepts
7 \ingroup qt-gui-concepts
8 \brief A tour of the standard layout managers and an introduction to custom
11 \previouspage Qt Widgets
12 \nextpage {Styles and Style Aware Widgets}{Styles}
14 \ingroup frameworks-technologies
16 The Qt layout system provides a simple and powerful way of automatically
17 arranging child widgets within a widget to ensure that they make good use
18 of the available space.
22 \section1 Introduction
24 Qt includes a set of layout management classes that are used to describe
25 how widgets are laid out in an application's user interface. These layouts
26 automatically position and resize widgets when the amount of space
27 available for them changes, ensuring that they are consistently arranged
28 and that the user interface as a whole remains usable.
30 All QWidget subclasses can use layouts to manage their children. The
31 QWidget::setLayout() function applies a layout to a widget. When a layout
32 is set on a widget in this way, it takes charge of the following tasks:
35 \li Positioning of child widgets
36 \li Sensible default sizes for windows
37 \li Sensible minimum sizes for windows
39 \li Automatic updates when contents change:
41 \li Font size, text or other contents of child widgets
42 \li Hiding or showing a child widget
43 \li Removal of child widgets
47 \section1 Qt's Layout Classes
49 Qt's layout classes were designed for hand-written C++ code, allowing
50 measurements to be specified in pixels for simplicity, so they are easy to
51 understand and use. The code generated for forms created using Qt Designer also
52 uses the layout classes. Qt Designer is useful to use when experimenting with the
53 design of a form since it avoids the compile, link and run cycle usually
54 involved in user interface development.
56 \annotatedlist geomanagement
58 \section1 Horizontal, Vertical, Grid, and Form Layouts
60 The easiest way to give your widgets a good layout is to use the built-in
61 layout managers: QHBoxLayout, QVBoxLayout, QGridLayout, and QFormLayout.
62 These classes inherit from QLayout, which in turn derives from QObject (not
63 QWidget). They take care of geometry management for a set of widgets. To
64 create more complex layouts, you can nest layout managers inside each other.
67 \li A QHBoxLayout lays out widgets in a horizontal row, from left to
68 right (or right to left for right-to-left languages).
69 \image qhboxlayout-with-5-children.png
71 \li A QVBoxLayout lays out widgets in a vertical column, from top to
73 \image qvboxlayout-with-5-children.png
75 \li A QGridLayout lays out widgets in a two-dimensional grid. Widgets
76 can occupy multiple cells.
77 \image qgridlayout-with-5-children.png
79 \li A QFormLayout lays out widgets in a 2-column descriptive label-
81 \image qformlayout-with-6-children.png
85 \section2 Laying Out Widgets in Code
87 The following code creates a QHBoxLayout that manages the geometry of five
88 \l{QPushButton}{QPushButtons}, as shown on the first screenshot above:
90 \snippet layouts/layouts.cpp 0
91 \snippet layouts/layouts.cpp 1
92 \snippet layouts/layouts.cpp 2
94 \snippet layouts/layouts.cpp 3
95 \snippet layouts/layouts.cpp 4
96 \snippet layouts/layouts.cpp 5
98 The code for QVBoxLayout is identical, except the line where the layout is
99 created. The code for QGridLayout is a bit different, because we need to
100 specify the row and column position of the child widget:
102 \snippet layouts/layouts.cpp 12
103 \snippet layouts/layouts.cpp 13
104 \snippet layouts/layouts.cpp 14
106 \snippet layouts/layouts.cpp 15
107 \snippet layouts/layouts.cpp 16
108 \snippet layouts/layouts.cpp 17
110 The third QPushButton spans 2 columns. This is possible by specifying 2 as
111 the fifth argument to QGridLayout::addWidget().
113 QFormLayout will add two widgets on a row, commonly a QLabel and a QLineEdit
114 to create forms. Adding a QLabel and a QLineEdit on the same row will set
115 the QLineEdit as the QLabel's buddy. The following code will use the
116 QFormLayout to place three \l{QPushButton}{QPushButtons} and a corresponding
119 \snippet layouts/layouts.cpp 18
120 \snippet layouts/layouts.cpp 19
121 \snippet layouts/layouts.cpp 20
123 \snippet layouts/layouts.cpp 21
124 \snippet layouts/layouts.cpp 22
125 \snippet layouts/layouts.cpp 23
128 \section2 Tips for Using Layouts
130 When you use a layout, you do not need to pass a parent when constructing
131 the child widgets. The layout will automatically reparent the widgets
132 (using QWidget::setParent()) so that they are children of the widget on
133 which the layout is installed.
135 \note Widgets in a layout are children of the widget on which the layout
136 is installed, \e not of the layout itself. Widgets can only have other
137 widgets as parent, not layouts.
139 You can nest layouts using \c addLayout() on a layout; the inner layout
140 then becomes a child of the layout it is inserted into.
143 \section1 Adding Widgets to a Layout
145 When you add widgets to a layout, the layout process works as follows:
148 \li All the widgets will initially be allocated an amount of space in
149 accordance with their QWidget::sizePolicy() and
152 \li If any of the widgets have stretch factors set, with a value
153 greater than zero, then they are allocated space in proportion to
154 their stretch factor (explained below).
156 \li If any of the widgets have stretch factors set to zero they will
157 only get more space if no other widgets want the space. Of these,
158 space is allocated to widgets with an
159 \l{QSizePolicy::Expanding}{Expanding} size policy first.
161 \li Any widgets that are allocated less space than their minimum size
162 (or minimum size hint if no minimum size is specified) are
163 allocated this minimum size they require. (Widgets don't have to
164 have a minimum size or minimum size hint in which case the stretch
165 factor is their determining factor.)
167 \li Any widgets that are allocated more space than their maximum size
168 are allocated the maximum size space they require. (Widgets do not
169 have to have a maximum size in which case the stretch factor is
170 their determining factor.)
174 \section2 Stretch Factors
175 \target stretch factor
177 Widgets are normally created without any stretch factor set. When they are
178 laid out in a layout the widgets are given a share of space in accordance
179 with their QWidget::sizePolicy() or their minimum size hint whichever is
180 the greater. Stretch factors are used to change how much space widgets are
181 given in proportion to one another.
183 If we have three widgets laid out using a QHBoxLayout with no stretch
184 factors set we will get a layout like this:
186 \image layout1.png Three widgets in a row
188 If we apply stretch factors to each widget, they will be laid out in
189 proportion (but never less than their minimum size hint), e.g.
191 \image layout2.png Three widgets with different stretch factors in a row
194 \section1 Custom Widgets in Layouts
196 When you make your own widget class, you should also communicate its layout
197 properties. If the widget uses one of Qt's layouts, this is already taken
198 care of. If the widget does not have any child widgets, or uses a manual
199 layout, you can change the behavior of the widget using any or all of the
200 following mechanisms:
203 \li Reimplement QWidget::sizeHint() to return the preferred size of the
205 \li Reimplement QWidget::minimumSizeHint() to return the smallest size
207 \li Call QWidget::setSizePolicy() to specify the space requirements of
211 Call QWidget::updateGeometry() whenever the size hint, minimum size hint or
212 size policy changes. This will cause a layout recalculation. Multiple
213 consecutive calls to QWidget::updateGeometry() will only cause one layout
216 If the preferred height of your widget depends on its actual width (e.g.,
217 a label with automatic word-breaking), set the
218 \l{QSizePolicy::hasHeightForWidth()}{height-for-width} flag in the
219 widget's \l{QWidget::sizePolicy}{size policy} and reimplement
220 QWidget::heightForWidth().
222 Even if you implement QWidget::heightForWidth(), it is still a good idea to
223 provide a reasonable sizeHint().
225 For further guidance when implementing these functions, see the
226 \e{Qt Quarterly} article
227 \l{http://doc.qt.io/archives/qq/qq04-height-for-width.html}
228 {Trading Height for Width}.
231 \section1 Layout Issues
233 The use of rich text in a label widget can introduce some problems to the
234 layout of its parent widget. Problems occur due to the way rich text is
235 handled by Qt's layout managers when the label is word wrapped.
237 In certain cases the parent layout is put into QLayout::FreeResize mode,
238 meaning that it will not adapt the layout of its contents to fit inside
239 small sized windows, or even prevent the user from making the window too
240 small to be usable. This can be overcome by subclassing the problematic
241 widgets, and implementing suitable \l{QWidget::}{sizeHint()} and
242 \l{QWidget::}{minimumSizeHint()} functions.
244 In some cases, it is relevant when a layout is added to a widget. When
245 you set the widget of a QDockWidget or a QScrollArea (with
246 QDockWidget::setWidget() and QScrollArea::setWidget()), the layout must
247 already have been set on the widget. If not, the widget will not be
251 \section1 Manual Layout
253 If you are making a one-of-a-kind special layout, you can also make a
254 custom widget as described above. Reimplement QWidget::resizeEvent() to
255 calculate the required distribution of sizes and call
256 \l{QWidget::}{setGeometry()} on each child.
258 The widget will get an event of type QEvent::LayoutRequest when the
259 layout needs to be recalculated. Reimplement QWidget::event() to handle
260 QEvent::LayoutRequest events.
263 \section1 How to Write A Custom Layout Manager
265 An alternative to manual layout is to write your own layout manager by
266 subclassing QLayout. The
267 \l{layouts/flowlayout}{Flow Layout} example shows how to do this.
269 Here we present an example in detail. The \c CardLayout class is inspired
270 by the Java layout manager of the same name. It lays out the items (widgets
271 or nested layouts) on top of each other, each item offset by
274 To write your own layout class, you must define the following:
276 \li A data structure to store the items handled by the layout. Each
277 item is a \l{QLayoutItem}{QLayoutItem}. We will use a
278 QList in this example.
279 \li \l{QLayout::}{addItem()}, how to add items to the layout.
280 \li \l{QLayout::}{setGeometry()}, how to perform the layout.
281 \li \l{QLayout::}{sizeHint()}, the preferred size of the layout.
282 \li \l{QLayout::}{itemAt()}, how to iterate over the layout.
283 \li \l{QLayout::}{takeAt()}, how to remove items from the layout.
286 In most cases, you will also implement \l{QLayout::}{minimumSize()}.
289 \section2 The Header File (\c card.h)
291 \snippet code/doc_src_layout.cpp 0
294 \section2 The Implementation File (\c card.cpp)
296 \snippet code/doc_src_layout.cpp 1
298 First we define \c{count()} to fetch the number of items in the list.
300 \snippet code/doc_src_layout.cpp 2
302 Then we define two functions that iterate over the layout: \c{itemAt()}
303 and \c{takeAt()}. These functions are used internally by the layout system
304 to handle deletion of widgets. They are also available for application
307 \c{itemAt()} returns the item at the given index. \c{takeAt()} removes the
308 item at the given index, and returns it. In this case we use the list index
309 as the layout index. In other cases where we have a more complex data
310 structure, we may have to spend more effort defining a linear order for the
313 \snippet code/doc_src_layout.cpp 3
315 \c{addItem()} implements the default placement strategy for layout items.
316 This function must be implemented. It is used by QLayout::add(), by the
317 QLayout constructor that takes a layout as parent. If your layout has
318 advanced placement options that require parameters, you must provide extra
319 access functions such as the row and column spanning overloads of
320 QGridLayout::addItem(), QGridLayout::addWidget(), and
321 QGridLayout::addLayout().
323 \snippet code/doc_src_layout.cpp 4
325 The layout takes over responsibility of the items added. Since QLayoutItem
326 does not inherit QObject, we must delete the items manually. In the
327 destructor, we remove each item from the list using \c{takeAt()}, and
330 \snippet code/doc_src_layout.cpp 5
332 The \c{setGeometry()} function actually performs the layout. The rectangle
333 supplied as an argument does not include \c{margin()}. If relevant, use
334 \c{spacing()} as the distance between items.
336 \snippet code/doc_src_layout.cpp 6
338 \c{sizeHint()} and \c{minimumSize()} are normally very similar in
339 implementation. The sizes returned by both functions should include
340 \c{spacing()}, but not \c{margin()}.
342 \snippet code/doc_src_layout.cpp 7
345 \section2 Further Notes
348 \li This custom layout does not handle height for width.
349 \li We ignore QLayoutItem::isEmpty(); this means that the layout will
350 treat hidden widgets as visible.
351 \li For complex layouts, speed can be greatly increased by caching
352 calculated values. In that case, implement
353 QLayoutItem::invalidate() to mark the cached data is dirty.
354 \li Calling QLayoutItem::sizeHint(), etc. may be expensive. So, you
355 should store the value in a local variable if you need it again
356 later within in the same function.
357 \li You should not call QLayoutItem::setGeometry() twice on the same
358 item in the same function. This call can be very expensive if the
359 item has several child widgets, because the layout manager must do
360 a complete layout every time. Instead, calculate the geometry and
361 then set it. (This does not only apply to layouts, you should do
362 the same if you implement your own resizeEvent(), for example.)
365 \section1 Layout Examples
367 Many Qt Widgets \l{Qt Widgets Examples}{examples} already use layouts,
368 however, several examples exist to showcase various layouts.
370 \annotatedlist examples-layout