Considering that mobile phones come in all shapes and sizes, it would be ridiculous to need to provide a different package for every different screen resolution. Hence we will use dynamic layouts.
Note
The source code can be found on the Git repository under the Chapter01-layouts
directory, in the cp1
branch.
Qt Widgets have support for this using classes such as QVBoxLayout
and QGridLayout
.
Qt Creator's designer is the easiest way to develop dynamic layouts. Let's go through how we can do that.
To set up a layout, we position a widget on the application form, and press Command or Control on the keyboard while selecting the widgets that we want to put in a layout. Here are two QPushButtons
selected for use:
Next, click on the Horizontal Layout
icon highlighted here:
You will then see the two widgets enclosed by a thin red box as in the following screenshot:
Now repeat this for the remaining widgets.
To make the widgets expand and resize with the form, click on the background and select Grid Layout:
Save and build this, and this app will now be able to resize for orientation changes as well as being able to work on different sized screens. Notice how this looks like in portrait (vertical) orientation:
Also note how this same application looks in landscape (horizontal) orientation:
As you can see, this application can change with orientation changes, but all the widgets are visible and usable. Using QSpacer
will help guide the widgets and layouts positioning. They can push the widgets together, apart, or hold some to one side or another.
Of course, layouts can be used without touching Qt Designer. For example the following code:
QPushButton *button = new QPushButton(this); QPushButton *button2 = new QPushButton(this); QBoxLayout *boxLayout =new QVBoxLayout; boxLayout->addWidget(button); boxLayout->addWidget(button2); QHBoxLayout *horizontalLayout = new QHBoxLayout; horizontalLayout->setLayout(boxLayout);
QLayout
and friends are the key to writing a cross-platform application that can accommodate the myriad screen resolutions and dynamically changing orientations of the target devices.