- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 340字
- 2021-08-27 18:30:54
Layouts
If you build and run the project now, you will see the window with two labels and a button, but they will remain in the exact positions you left them. This is what you almost never want. Usually, it is desired that widgets are automatically resized based on their content and the size of their neighbors. They need to adjust to the changes of the window's size (or, in contrast, the window size may need to be restricted based on possible sizes of the widgets inside of it). This is a very important feature for a cross-platform application, as you cannot assume any particular screen resolution or size of controls. In Qt, all of this requires us to use a special mechanism called layouts.
Layouts allow us to arrange the content of a widget, ensuring that its space is used efficiently. When we set a layout on a widget, we can start adding widgets, and even other layouts, and the mechanism will resize and reposition them according to the rules that we specify. When something happens in the user interface that influences how widgets should be displayed (for example, the label text is replaced with longer text, which makes the label require more space to show its content), the layout is triggered again, which recalculates all positions and sizes and updates widgets, as necessary.
Qt comes with a predefined set of layouts that are derived from the QLayout class, but you can also create your own. The ones that we already have at our disposal are QHBoxLayout and QVBoxLayout, which position items horizontally and vertically; QGridLayout, which arranges items in a grid so that an item can span across columns or rows; and QFormLayout, which creates two columns of items with item descriptions in one column and item content in the other. There is also QStackedLayout, which is rarely used directly and which makes one of the items assigned to it possess all the available space. You can see the most common layouts in action in the following figure: