Qt 布局系统提供在 Widget 中自动排列子级小部件的简单、强大方式,以确保它们很好地使用可用空间。
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.
所有 QWidget subclasses can use layouts to manage their children. The QWidget::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:
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.
水平或垂直排列子级 Widget | |
用于组织按钮 Widget 组的容器 | |
管理输入 Widget 表单及其关联标签 | |
表示 QGraphicsAnchorLayout 中 2 项之间的锚点 | |
可以在图形视图中将 Widget 锚定在一起的布局 | |
在栅格中布局 Widget | |
带标题的分组框框架 | |
水平排列 Widget | |
几何管理器的基类 | |
操纵 QLayout 的抽象项 | |
描述水平和垂直重置大小策略的布局属性 | |
布局中的空白空间 | |
每次仅一 Widget 可见的 Widget 堆栈 | |
每次仅一 Widget 可见的 Widget 堆栈 | |
垂直排列 Widget | |
表示 Widget 的布局项 |
The easiest way to give your widgets a good layout is to use the built-in layout managers: QHBoxLayout , QVBoxLayout , QGridLayout ,和 QFormLayout . These classes inherit from QLayout ,依次派生自 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.
以下代码创建 QHBoxLayout that manages the geometry of five QPushButtons , as shown on the first screenshot above:
QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); QHBoxLayout *layout = new 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:
QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); QGridLayout *layout = new 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 QGridLayout::addWidget ().
QFormLayout will add two widgets on a row, commonly a QLabel 和 QLineEdit to create forms. Adding a QLabel 和 QLineEdit on the same row will set the QLineEdit 作为 QLabel 's buddy. The following code will use the QFormLayout to place three QPushButtons and a corresponding QLineEdit on a row.
QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QLineEdit *lineEdit1 = new QLineEdit(); QPushButton *button2 = new QPushButton("Two"); QLineEdit *lineEdit2 = new QLineEdit(); QPushButton *button3 = new QPushButton("Three"); QLineEdit *lineEdit3 = new QLineEdit(); QFormLayout *layout = new QFormLayout(window); layout->addRow(button1, lineEdit1); layout->addRow(button2, lineEdit2); layout->addRow(button3, lineEdit3); window->show();
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 QWidget::setParent ()) so that they are children of the widget on which the layout is installed.
注意: 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.
When you add widgets to a layout, the layout process works as follows:
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 QWidget::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:
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.
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:
调用 QWidget::updateGeometry () whenever the size hint, minimum size hint or size policy changes. This will cause a layout recalculation. Multiple consecutive calls to QWidget::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 并重实现 QWidget::heightForWidth ().
Even if you implement QWidget::heightForWidth (), it is still a good idea to provide a reasonable sizeHint().
For further guidance when implementing these functions, see the Qt 季刊 文章 交易高度为宽度 .
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 () 和 minimumSizeHint () 函数。
In some cases, it is relevant when a layout is added to a widget. When you set the widget of a QDockWidget 或 QScrollArea (with QDockWidget::setWidget () 和 QScrollArea::setWidget ()), the layout must already have been set on the widget. If not, the widget will not be visible.
If you are making a one-of-a-kind special layout, you can also make a custom widget as described above. Reimplement QWidget::resizeEvent () to calculate the required distribution of sizes and call setGeometry () on each child.
The widget will get an event of type QEvent::LayoutRequest when the layout needs to be recalculated. Reimplement QWidget::event () to handle QEvent::LayoutRequest 事件。
An alternative to manual layout is to write your own layout manager by subclassing QLayout 。 流式布局 example shows 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
QLayout::spacing
().
To write your own layout class, you must define the following:
In most cases, you will also implement minimumSize ().
card.h
)
#ifndef CARD_H #define CARD_H #include <QtWidgets> #include <QList> class CardLayout : public QLayout { public: CardLayout(int spacing): QLayout() { setSpacing(spacing); } CardLayout(int spacing, QWidget *parent): QLayout(parent) { setSpacing(spacing); } ~CardLayout(); void addItem(QLayoutItem *item) override; QSize sizeHint() const override; QSize minimumSize() const override; int count() const override; QLayoutItem *itemAt(int) const override; QLayoutItem *takeAt(int) override; void setGeometry(const QRect &rect) override; private: QList<QLayoutItem *> m_items; }; #endif
card.cpp
)
//#include "card.h"
首先定义
count()
to fetch the number of items in the list.
int CardLayout::count() const { // 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) const { // 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 && idx < m_items.size() ? m_items.takeAt(idx) : 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
QGridLayout::addItem
(),
QGridLayout::addWidget
(),和
QGridLayout::addLayout
().
void CardLayout::addItem(QLayoutItem *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() { QLayoutItem *item; while ((item = takeAt(0))) delete 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.
void CardLayout::setGeometry(const QRect &r) { QLayout::setGeometry(r); if (m_items.size() == 0) return; int w = r.width() - (m_items.count() - 1) * spacing(); int h = r.height() - (m_items.count() - 1) * spacing(); int i = 0; while (i < m_items.size()) { QLayoutItem *o = m_items.at(i); QRect geom(r.x() + i * spacing(), r.y() + i * spacing(), w, h); o->setGeometry(geom); ++i; } }
sizeHint()
and
minimumSize()
are normally very similar in implementation. The sizes returned by both functions should include
spacing()
, but not
margin()
.
QSize CardLayout::sizeHint() const { QSize s(0, 0); int n = m_items.count(); if (n > 0) s = QSize(100, 70); //start with a nice default size int i = 0; while (i < n) { QLayoutItem *o = m_items.at(i); s = s.expandedTo(o->sizeHint()); ++i; } return s + n * QSize(spacing(), spacing()); } QSize CardLayout::minimumSize() const { QSize s(0, 0); int n = m_items.count(); int i = 0; while (i < n) { QLayoutItem *o = m_items.at(i); s = s.expandedTo(o->minimumSize()); ++i; } return s + n * QSize(spacing(), spacing()); }
很多 Qt Widgets examples 已使用布局,不管怎样,存在几个范例能陈列各种布局。
范例展示如何使用信号/槽来实现计算器 Widget 功能,及如何使用 QGridLayout 将子级小部件放在栅格中。 | |
日历 Widget 范例展示使用 QCalendarWidget。 | |
Shows how to arrange widgets for different window sizes. | |
Shows how composition modes work in QPainter. | |
The Menus example demonstrates how menus can be used in a main window application. | |
The Simple Tree Model example shows how to use a hierarchical model with Qt's standard view classes. |