source: trunk/doc/src/layout.qdoc@ 109

Last change on this file since 109 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 16.2 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \page layout.html
44
45 \title Layout Classes
46 \ingroup architecture
47 \ingroup classlists
48 \brief A tour of the standard layout managers and an introduction to custom
49 layouts.
50
51 The Qt layout system provides a simple and powerful way of automatically
52 arranging child widgets within a widget to ensure that they make good use
53 of the available space.
54
55 \tableofcontents
56
57 \section1 Introduction
58
59 Qt includes a set of layout management classes that are used to describe
60 how widgets are laid out in an application's user interface. These layouts
61 automatically position and resize widgets when the amount of space
62 available for them changes, ensuring that they are consistently arranged
63 and that the user interface as a whole remains usable.
64
65 All QWidget subclasses can use layouts to manage their children. The
66 QWidget::setLayout() function applies a layout to a widget. When a layout
67 is set on a widget in this way, it takes charge of the following tasks:
68
69 \list
70 \o Positioning of child widgets.
71 \o Sensible default sizes for windows.
72 \o Sensible minimum sizes for windows.
73 \o Resize handling.
74 \o Automatic updates when contents change:
75 \list
76 \o Font size, text or other contents of child widgets.
77 \o Hiding or showing a child widget.
78 \o Removal of child widgets.
79 \endlist
80 \endlist
81
82 Qt's layout classes were designed for hand-written C++ code, allowing
83 measurements to be specified in pixels for simplicity, so they are easy to
84 understand and use. The code generated for forms created using \QD also
85 uses the layout classes. \QD is useful to use when experimenting with the
86 design of a form since it avoids the compile, link and run cycle usually
87 involved in user interface development.
88
89
90 \section1 Horizontal, Vertical, Grid, and Form Layouts
91
92 The easiest way to give your widgets a good layout is to use the built-in
93 layout managers: QHBoxLayout, QVBoxLayout, QGridLayout, and QFormLayout.
94 These classes inherit from QLayout, which in turn derives from QObject (not
95 QWidget). They take care of geometry management for a set of widgets. To
96 create more complex layouts, you can nest layout managers inside each other.
97
98 \list
99 \o A QHBoxLayout lays out widgets in a horizontal row, from left to
100 right (or right to left for right-to-left languages).
101 \image qhboxlayout-with-5-children.png
102
103 \o A QVBoxLayout lays out widgets in a vertical column, from top to
104 bottom.
105 \image qvboxlayout-with-5-children.png
106
107 \o A QGridLayout lays out widgets in a two-dimensional grid. Widgets
108 can occupy multiple cells.
109 \image qgridlayout-with-5-children.png
110
111 \o A QFormLayout lays out widgets in a 2-column descriptive label-
112 field style.
113 \image qformlayout-with-6-children.png
114 \endlist
115
116
117 \section2 Laying Out Widgets in Code
118
119 The following code creates a QHBoxLayout that manages the geometry of five
120 \l{QPushButton}s, as shown on the first screenshot above:
121
122 \snippet doc/src/snippets/layouts/layouts.cpp 0
123 \snippet doc/src/snippets/layouts/layouts.cpp 1
124 \snippet doc/src/snippets/layouts/layouts.cpp 2
125 \codeline
126 \snippet doc/src/snippets/layouts/layouts.cpp 3
127 \snippet doc/src/snippets/layouts/layouts.cpp 4
128 \snippet doc/src/snippets/layouts/layouts.cpp 5
129
130 The code for QVBoxLayout is identical, except the line where the layout is
131 created. The code for QGridLayout is a bit different, because we need to
132 specify the row and column position of the child widget:
133
134 \snippet doc/src/snippets/layouts/layouts.cpp 12
135 \snippet doc/src/snippets/layouts/layouts.cpp 13
136 \snippet doc/src/snippets/layouts/layouts.cpp 14
137 \codeline
138 \snippet doc/src/snippets/layouts/layouts.cpp 15
139 \snippet doc/src/snippets/layouts/layouts.cpp 16
140 \snippet doc/src/snippets/layouts/layouts.cpp 17
141
142 The third QPushButton spans 2 columns. This is possible by specifying 2 as
143 the fifth argument to QGridLayout::addWidget().
144
145 Finally, the code for QFormLayout is ..
146
147
148 \section2 Tips for Using Layouts
149
150 When you use a layout, you do not need to pass a parent when constructing
151 the child widgets. The layout will automatically reparent the widgets
152 (using QWidget::setParent()) so that they are children of the widget on
153 which the layout is installed.
154
155 \note Widgets in a layout are children of the widget on which the layout
156 is installed, \e not of the layout itself. Widgets can only have other
157 widgets as parent, not layouts.
158
159 You can nest layouts using \c addLayout() on a layout; the inner layout
160 then becomes a child of the layout it is inserted into.
161
162
163 \section1 Adding Widgets to a Layout
164
165 When you add widgets to a layout, the layout process works as follows:
166
167 \list 1
168 \o All the widgets will initially be allocated an amount of space in
169 accordance with their QWidget::sizePolicy() and
170 QWidget::sizeHint().
171
172 \o If any of the widgets have stretch factors set, with a value
173 greater than zero, then they are allocated space in proportion to
174 their stretch factor (explained below).
175
176 \o If any of the widgets have stretch factors set to zero they will
177 only get more space if no other widgets want the space. Of these,
178 space is allocated to widgets with an
179 \l{QSizePolicy::Expanding}{Expanding} size policy first.
180
181 \o Any widgets that are allocated less space than their minimum size
182 (or minimum size hint if no minimum size is specified) are
183 allocated this minimum size they require. (Widgets don't have to
184 have a minimum size or minimum size hint in which case the strech
185 factor is their determining factor.)
186
187 \o Any widgets that are allocated more space than their maximum size
188 are allocated the maximum size space they require. (Widgets do not
189 have to have a maximum size in which case the strech factor is
190 their determining factor.)
191 \endlist
192
193
194 \section2 Stretch Factors
195 \keyword stretch factor
196
197 Widgets are normally created without any stretch factor set. When they are
198 laid out in a layout the widgets are given a share of space in accordance
199 with their QWidget::sizePolicy() or their minimum size hint whichever is
200 the greater. Stretch factors are used to change how much space widgets are
201 given in proportion to one another.
202
203 If we have three widgets laid out using a QHBoxLayout with no stretch
204 factors set we will get a layout like this:
205
206 \img layout1.png Three widgets in a row
207
208 If we apply stretch factors to each widget, they will be laid out in
209 proportion (but never less than their minimum size hint), e.g.
210
211 \img layout2.png Three widgets with different stretch factors in a row
212
213
214 \section1 Custom Widgets in Layouts
215
216 When you make your own widget class, you should also communicate its layout
217 properties. If the widget has a one of Qt's layouts, this is already taken
218 care of. If the widget does not have any child widgets, or uses manual
219 layout, you can change the behavior of the widget using any or all of the
220 following mechanisms:
221
222 \list
223 \o Reimplement QWidget::sizeHint() to return the preferred size of the
224 widget.
225 \o Reimplement QWidget::minimumSizeHint() to return the smallest size
226 the widget can have.
227 \o Call QWidget::setSizePolicy() to specify the space requirements of
228 the widget.
229 \endlist
230
231 Call QWidget::updateGeometry() whenever the size hint, minimum size hint or
232 size policy changes. This will cause a layout recalculation. Multiple
233 consecutive calls to QWidget::updateGeometry() will only cause one layout
234 recalculation.
235
236 If the preferred height of your widget depends on its actual width (e.g.,
237 a label with automatic word-breaking), set the
238 \l{QSizePolicy::hasHeightForWidth()}{height-for-width} flag in the
239 widget's \l{QWidget::sizePolicy}{size policy} and reimplement
240 QWidget::heightForWidth().
241
242 Even if you implement QWidget::heightForWidth(), it is still a good idea to
243 provide a reasonable sizeHint().
244
245 For further guidance when implementing these functions, see the
246 \e{Qt Quarterly} article
247 \l{http://doc.trolltech.com/qq/qq04-height-for-width.html}
248 {Trading Height for Width}.
249
250
251 \section1 Layout Issues
252
253 The use of rich text in a label widget can introduce some problems to the
254 layout of its parent widget. Problems occur due to the way rich text is
255 handled by Qt's layout managers when the label is word wrapped.
256
257 In certain cases the parent layout is put into QLayout::FreeResize mode,
258 meaning that it will not adapt the layout of its contents to fit inside
259 small sized windows, or even prevent the user from making the window too
260 small to be usable. This can be overcome by subclassing the problematic
261 widgets, and implementing suitable \l{QWidget::}{sizeHint()} and
262 \l{QWidget::}{minimumSizeHint()} functions.
263
264 In some cases, it is relevant when a layout is added to a widget. When
265 you set the widget of a QDockWidget or a QScrollArea (with
266 QDockWidget::setWidget() and QScrollArea::setWidget()), the layout must
267 already have been set on the widget. If not, the widget will not be
268 visible.
269
270
271 \section1 Manual Layout
272
273 If you are making a one-of-a-kind special layout, you can also make a
274 custom widget as described above. Reimplement QWidget::resizeEvent() to
275 calculate the required distribution of sizes and call
276 \l{QWidget::}{setGeometry()} on each child.
277
278 The widget will get an event of type QEvent::LayoutRequest when the
279 layout needs to be recalculated. Reimplement QWidget::event() to handle
280 QEvent::LayoutRequest events.
281
282
283 \section1 How to Write A Custom Layout Manager
284
285 An alternative to manual layout is to write your own layout manager by
286 subclassing QLayout. The \l{layouts/borderlayout}{Border Layout} and
287 \l{layouts/flowlayout}{Flow Layout} examples show how to do this.
288
289 Here we present an example in detail. The \c CardLayout class is inspired
290 by the Java layout manager of the same name. It lays out the items (widgets
291 or nested layouts) on top of each other, each item offset by
292 QLayout::spacing().
293
294 To write your own layout class, you must define the following:
295 \list
296 \o A data structure to store the items handled by the layout. Each
297 item is a \link QLayoutItem QLayoutItem\endlink. We will use a
298 QList in this example.
299 \o \l{QLayout::}{addItem()}, how to add items to the layout.
300 \o \l{QLayout::}{setGeometry()}, how to perform the layout.
301 \o \l{QLayout::}{sizeHint()}, the preferred size of the layout.
302 \o \l{QLayout::}{itemAt()}, how to iterate over the layout.
303 \o \l{QLayout::}{takeAt()}, how to remove items from the layout.
304 \endlist
305
306 In most cases, you will also implement \l{QLayout::}{minimumSize()}.
307
308
309 \section2 The Header File (\c card.h)
310
311 \snippet doc/src/snippets/code/doc_src_layout.qdoc 0
312
313
314 \section2 The Implementation File (\c card.cpp)
315
316 \snippet doc/src/snippets/code/doc_src_layout.qdoc 1
317
318 First we define two functions that iterate over the layout: \c{itemAt()}
319 and \c{takeAt()}. These functions are used internally by the layout system
320 to handle deletion of widgets. They are also available for application
321 programmers.
322
323 \c{itemAt()} returns the item at the given index. \c{takeAt()} removes the
324 item at the given index, and returns it. In this case we use the list index
325 as the layout index. In other cases where we have a more complex data
326 structure, we may have to spend more effort defining a linear order for the
327 items.
328
329 \snippet doc/src/snippets/code/doc_src_layout.qdoc 2
330
331 \c{addItem()} implements the default placement strategy for layout items.
332 This function must be implemented. It is used by QLayout::add(), by the
333 QLayout constructor that takes a layout as parent. If your layout has
334 advanced placement options that require parameters, you must provide extra
335 access functions such as the row and column spanning overloads of
336 QGridLayout::addItem(), QGridLayout::addWidget(), and
337 QGridLayout::addLayout().
338
339 \snippet doc/src/snippets/code/doc_src_layout.qdoc 3
340
341 The layout takes over responsibility of the items added. Since QLayoutItem
342 does not inherit QObject, we must delete the items manually. The function
343 QLayout::deleteAllItems() uses \c{takeAt()} defined above to delete all the
344 items in the layout.
345
346 \snippet doc/src/snippets/code/doc_src_layout.qdoc 4
347
348 The \c{setGeometry()} function actually performs the layout. The rectangle
349 supplied as an argument does not include \c{margin()}. If relevant, use
350 \c{spacing()} as the distance between items.
351
352 \snippet doc/src/snippets/code/doc_src_layout.qdoc 5
353
354 \c{sizeHint()} and \c{minimumSize()} are normally very similar in
355 implementation. The sizes returned by both functions should include
356 \c{spacing()}, but not \c{margin()}.
357
358 \snippet doc/src/snippets/code/doc_src_layout.qdoc 6
359
360
361 \section2 Further Notes
362
363 \list
364 \o This custom layout does not handle height for width.
365 \o We ignore QLayoutItem::isEmpty(); this means that the layout will
366 treat hidden widgets as visible.
367 \o For complex layouts, speed can be greatly increased by caching
368 calculated values. In that case, implement
369 QLayoutItem::invalidate() to mark the cached data is dirty.
370 \o Calling QLayoutItem::sizeHint(), etc. may be expensive. So, you
371 should store the value in a local variable if you need it again
372 later within in the same function.
373 \o You should not call QLayoutItem::setGeometry() twice on the same
374 item in the smae function. This call can be very expensive if the
375 item has several child widgets, because the layout manager must do
376 a complete layout every time. Instead, calculate the geometry and
377 then set it. (This does not only apply to layouts, you should do
378 the same if you implement your own resizeEvent(), for example.)
379 \endlist
380*/
381
Note: See TracBrowser for help on using the repository browser.