I thought that layout is just a widget that keeps more widgets inside. But now I find that I can't add it to other widgets using addWidget. For instance how to add a layout to QSplitter?
No, a layout is not a widget or a container. A layout is more like a "helper" that's attached to a window and figures out the best place to put each widget.
This example from the Qt docs should help (http://qt.nokia.com/doc/4.2/layout.html):
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;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);
window->setLayout(layout);
window->show();
QLayout
s are layout managers. They manage the positioning and resizing of widgets inside a parent widget. From the docs:
Layouts are an elegant and flexible way to automatically arrange child widgets within their container. Each widget reports its size requirements to the layout through the sizeHint and sizePolicy properties, and the layout distributes the available space accordingly.
For example, setting the layout of a widget to QHBoxLayout
will result in its child widgets being laid out horizontally.
You can read more about it here.
QWidget has built in support for layouts through the layout()
and setLayout(...)
functions. The layout object controls the positioning of different child widgets that may be added to the layout. In addition, it makes sure to correctly size its parent widget based on the constraints specified. If the layout does not yet have a parent widget, then as soon as the layout is attached to a widget with setLayout()
, it will set the size of that parent widget.
But, some widgets are more like a layout manager than a widget, such as QSplitter and QTabWidget. Consider, for example, QSplitter. Although a single widget, it presents two different areas that may be worked with. In this case, a single layout manager for two different areas doesn't really make sense. Like QSplitter, QTabWidget has some behaviors which make a single layout not only unnecessary but not useful.
I think it's the above melding of layout and widget that makes the separation of layout and widget sometimes confusing.