Despite all of the benefits that QML and Qt Quick offer, they can be challenging in certain situations. The following sections elaborate on some of the best practices that will help you get better results when developing applications.
A fluid and modern UI is key for any application's success in today's world, and that's where QML makes so much sense for a designer or developer. Qt offers the most basic UI controls that are necessary to create a fluid and modern-looking UI. It is recommended to browse this list of UI controls before creating your own custom UI control.
Besides these basic UI controls offered by Qt Quick itself, a rich set of UI controls are also available with Qt Quick Controls. They cater to the most common use cases without any change, and offer a lot more possibilities with their customization options. In particular, Qt Quick Controls provides styling options that align with the latest UI design trends. If these UI controls do not satisfy your application's needs, only then it is recommended to create a custom control.
You can use the controls when you design UIs in Qt Design Studio. In addition, it provides timeline-based animations, visual effects, layouts, and a live-preview for prototyping applications.
见 QML 编码约定 .
Most applications depend on resources such as images and icons to provide a rich user experience. It can often be a challenge to make these resources available to the application regardless of the target OS. Most popular OS-es employ stricter security policies that restrict access to the file system, making it harder to load these resources. As an alternative, Qt offers its own 资源系统 that is built into the application binary, enabling access to the application's resources regardless of the target OS.
For example, consider the following project directory structure:
project ├── images │ ├── image1.png │ └── image2.png ├── project.pro └── qml └── main.qml
The following entry in
project.pro
ensures that the resources are built into the application binary, making them available when needed:
RESOURCES += \ qml/main.qml \ images/image1.png \ images/image2.png
A more convenient approach is to use the wildcard syntax to select several files at once:
RESOURCES += \ $$files(qml/*.qml) \ $$files(images/*.png)
This approach is convenient for applications that depend on a limited number of resources. However, whenever a new file is added to
RESOURCES
using this approach, it causes
all
of the other files in
RESOURCES
to be recompiled as well. This can be inefficient, especially for large sets of files. In this case, a better approach is to separate each type of resource into its own
.qrc
file. For example, the snippet above could be changed to the following:
qml.files = $$files(*.qml) qml.prefix = /qml RESOURCES += qml images.files = $$files(*.png) images.prefix = /images RESOURCES += images
Now, whenever a QML file is changed, only the QML files have to be recompiled.
Sometimes it can be necessary to have more control over the path for a specific file managed by the resource system. For example, if we wanted to give
image2.png
an alias, we would need to switch to an explicit
.qrc
文件。
Creating Resource Files
explains how to do this in detail.
One of the key goals that most application developers want to achieve is to create a maintainable application. One of the ways to achieve this goal is to separate the user interface from the business logic. The following are a few reasons why an application's UI should be written in QML:
Being a strongly typed language, C++ is best suited for an application's business logic. Typically, such code performs tasks such as complex calculations or data processing, which are faster in C++ than QML.
Qt offers various approaches to integrate QML and C++ code in an application. A typical use case is displaying a list of data in a user interface. If the data set is static, simple, and/or small, a model written in QML can be sufficient.
The following snippet demonstrates examples of models written in QML:
model: ListModel { ListElement { name: "Item 1" } ListElement { name: "Item 2" } ListElement { name: "Item 3" } } model: [ "Item 1", "Item 2", "Item 3" ] model: 10
使用 C++ for dynamic data sets that are large or frequently modified.
Although Qt enables you to manipulate QML from C++, it is not recommended to do so. To explain why, let's take a look at a simplified example.
Suppose we were writing the UI for a settings page:
import QtQuick 2.15 import QtQuick.Controls 2.15 Page { Button { text: qsTr("Restore default settings") } }
We want the button to do something in C++ when it is clicked. We know objects in QML can emit change signals just like they can in C++, so we give the button an objectName so that we can find it from C++:
Button { objectName: "restoreDefaultsButton" text: qsTr("Restore default settings") }
Then, in C++, we find that object and connect to its change signal:
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QSettings> class Backend : public QObject { Q_OBJECT public: Backend() {} public slots: void restoreDefaults() { settings.setValue("loadLastProject", QVariant(false)); } private: QSettings settings; }; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; Backend backend; QObject *rootObject = engine.rootObjects().first(); QObject *restoreDefaultsButton = rootObject->findChild<QObject*>("restoreDefaultsButton"); QObject::connect(restoreDefaultsButton, SIGNAL(clicked()), &backend, SLOT(restoreDefaults())); return app.exec(); } #include "main.moc"
With this approach, references to objects are "pulled" from QML. The problem with this is that the C++ logic layer depends on the QML presentation layer. If we were to refactor the QML in such a way that the
objectName
changes, or some other change breaks the ability for the C++ to find the QML object, our workflow becomes much more complicated and tedious.
Refactoring QML is a lot easier than refactoring C++, so in order to make maintenance pain-free, we should strive to keep C++ types unaware of QML as much as possible. This can be achieved by "pushing" references to C++ types into QML:
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); Backend backend; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("backend", &backend); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
The QML then calls the C++ slot directly:
import QtQuick 2.15 import QtQuick.Controls 2.15 Page { Button { text: qsTr("Restore default settings") onClicked: backend.restoreDefaults() } }
With this approach, the C++ remains unchanged in the event that the QML needs to be refactored in the future.
In the example above, we set a context property on the root context to expose the C++ object to QML. This means that the property is available to every component loaded by the engine. Context properties are useful for objects that must be available as soon as the QML is loaded and cannot be instantiated in QML.
For a quick guide to choosing the correct approach to expose C++ types to QML, see Choosing the Correct Integration Method Between C++ and QML .
Qt Design Studio uses UI files that have the filename extension .ui.qml to separate the visual parts of the UI from the UI logic you implement in .qml files. You should edit UI files only in the 2D view in Qt Design Studio. If you use some other tool to add code that Qt Design Studio does not support, it displays error messages. Fix the errors to enable visual editing of the UI files again. Typically, you should move the unsupported code to a .qml 文件。
Qt offers Qt Quick Layouts to arrange Qt Quick items visually in a layout. Unlike its alternative, the item positioners, the Qt Quick Layouts can also resize its children on window resize. Although Qt Quick Layouts are often the desired choice for most use cases, the following dos and don'ts must be considered while using them:
Layout.preferredWidth
and
Layout.preferredHeight
:
RowLayout { id : layout anchors .fill: parent spacing : 6 Rectangle { color : 'azure' Layout .fillWidth: true Layout .minimumWidth: 50 Layout .preferredWidth: 100 Layout .maximumWidth: 300 Layout .minimumHeight: 150 Text { anchors .centerIn: parent text : parent . width + 'x' + parent . height } } Rectangle { color : 'plum' Layout .fillWidth: true Layout .minimumWidth: 100 Layout .preferredWidth: 200 Layout .preferredHeight: 100 Text { anchors .centerIn: parent text : parent . width + 'x' + parent . height } } }
注意: Layouts and anchors are both types of objects that take more memory and instantiation time. Avoid using them (especially in list and table delegates, and styles for controls) when simple bindings to x, y, width, and height properties are enough.
When declaring properties in QML, it's easy and convenient to use the "var" type:
property var name property var size property var optionsMenu
However, this approach has several disadvantages:
Instead, always use the actual type where possible:
property string name property int size property MyMenu optionsMenu
For information on performance in QML and Qt Quick, see 性能注意事项和建议 .
In QML, it's possible to use imperative JavaScript code to perform tasks such as responding to input events, send data over a network, and so on. Imperative code has an important place in QML, but it's also important to be aware of when not to use it.
For example, consider the following imperative assignment:
Rectangle { Component.onCompleted: color = "red" }
This has the following disadvantages:
The code can be rewritten to be a declarative binding instead:
Rectangle { color: "red" }
For information on useful tools and utilies that make working with QML and Qt Quick easier, see Qt Quick 工具和实用程序 .
Qt Quick 场景图形的有关信息,见 Qt Quick 场景图形 .
As display resolutions improve, a scalable application UI becomes more and more important. One of the approaches to achieve this is to maintain several copies of the UI for different screen resolutions, and load the appropriate one depending on the available resolution. Although this works pretty well, it adds to the maintenance overhead.
Qt offers a better solution to this problem and recommends the application developers to follow these tips:
qt-logo.png
for
@2x
,
@3x
,和
@4x
resolutions, enabling the application to cater to high resolution displays. Qt automatically chooses the appropriate image that is suitable for the given display, provided the high DPI scaling feature is explicitly enabled.
With this in place, your application's UI should scale depending on the display resolution on offer.