Qt : what is the difference between layout and widget?

浪子不回头ぞ 提交于 2019-12-23 08:46:10

问题


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?


回答1:


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.




回答2:


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();



回答3:


QLayouts 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.



来源:https://stackoverflow.com/questions/2609078/qt-what-is-the-difference-between-layout-and-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!