Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
qtquick-bestpractices.qdoc
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\page qtquick-bestpractices.html
6\title Best Practices for QML and Qt Quick
7\brief Lists best practices for working with QML and Qt Quick.
8\ingroup best-practices
9
10Despite all of the benefits that QML and Qt Quick offer, they can be
11challenging in certain situations. The following sections elaborate on some of
12the best practices that will help you get better results when developing
13applications.
14
15\section1 Custom UI Controls
16
17A fluid and modern UI is key for any application's success in today's world, and
18that's where QML makes so much sense for a designer or developer. Qt offers the
19most basic UI controls that are necessary to create a fluid and modern-looking
20UI. It is recommended to browse this list of UI controls before creating your
21own custom UI control.
22
23Besides these basic UI controls offered by Qt Quick itself, a rich set of UI
24controls are also available with Qt Quick Controls. They cater to the most
25common use cases without any change, and offer a lot more possibilities with their
26customization options. In particular, Qt Quick Controls provides styling
27options that align with the latest UI design trends. If these UI controls do not
28satisfy your application's needs, only then it is recommended to create a
29custom control.
30
31You can use the controls when you design UIs in Qt Design Studio. In addition,
32it provides timeline-based animations, visual effects, layouts, and a
33live-preview for prototyping applications.
34
35\section2 Related Information
36\list
37\li \l{Qt Quick Controls}
38\li \l{Customizing Qt Quick Controls}
39\li \l{Qt Quick}
40\li \l{Qt Design Studio Manual}
41\endlist
42
43\omit
44\section1 Keep it Short and Simple or "KiSS"
45
46QML being a declarative language, a lot of the details are worked out by the underlying
47engine. So it is important for any QML application, especially one with a
48larger codebase, to have its code organized in smaller and simpler \c .qml files.
49
50TODO: need a few snippet or example applications that showcase this.
51\endomit
52
53\section1 Coding Conventions
54
55See \l{QML Coding Conventions}.
56
57\section1 Bundle Application Resources
58
59Most applications depend on resources such as images and icons to provide a
60rich user experience. It can often be a challenge to make these resources
61available to the application regardless of the target OS. Most popular OS-es
62employ stricter security policies that restrict access to the file system,
63making it harder to load these resources. As an alternative, Qt offers its own
64\l {The Qt Resource System}{resource system} that is built into the
65application binary, enabling access to the application's resources regardless
66of the target OS.
67
68For example, consider the following project directory structure:
69
70\badcode
71MyModule
72├── images
73│ ├── image1.png
74│ └── image2.png
75├── CMakeLists.txt
76└── main.qml
77\endcode
78
79You may represent this structure as a \l{qt_add_qml_module}{CMake QML Module} in the following way:
80
81\code
82qt_add_qml_module(my_module
83 URI MyModule
84 VERSION 1.0
85 QML_FILES
86 main.qml
87 RESOURCES
88 images/image1.png
89 images/image2.png
90 # ...
91)
92\endcode
93
94All QML files listed under \c {QML_FILES} will automatically get compiled \l {Ahead-of-Time Compilation}{ahead of time}.
95
96You should keep the QML files in the same directory as the CMakeLists.txt with
97the qt_add_qml_module. Otherwise their \l{The Implicit Import}{implicit imports}
98will be different from the \l{QML Modules} they belong to. This is a frequent
99source of mistakes.
100
101\section2 Related Information
102\list
103 \li \l{The Qt Resource System}
104\endlist
105
106\section1 Separate UI from Business Logic
107
108One of the key goals that most application developers want to achieve is to
109create a maintainable application. One of the ways to achieve this goal is
110to separate the user interface from the business logic. The following are a few
111reasons why an application's UI should be written in QML:
112
113\list
114 \li Declarative languages are strongly suited for defining UIs.
115 \li QML code is simpler to write, as it is less verbose than C++, and is not
116 strongly typed. This also results in it being an excellent language to
117 prototype in, a quality that is vital when collaborating with designers,
118 for example.
119 \li JavaScript can easily be used in QML to respond to events.
120\endlist
121
122Being a strongly typed language, C++ is best suited for an application's
123business logic. Typically, such code performs tasks such as complex calculations
124or data processing, which are faster in C++ than QML.
125
126Qt offers various approaches to integrate QML and C++ code in an application.
127A typical use case is displaying a list of data in a user interface.
128If the data set is static, simple, and/or small, a model written in QML can be
129sufficient.
130
131The following snippet demonstrates examples of models written in QML:
132
133\qml
134 model: [ "Item 1", "Item 2", "Item 3" ]
135
136 model: 10
137\endqml
138
139Use \l {QAbstractItemModel Subclass}{C++} for dynamic data sets that are large
140or frequently modified.
141
142\section2 Exposing Data from C++ to QML
143
144Refactoring QML is a lot easier than refactoring C++, so in order to make
145maintenance pain-free, we should strive to keep C++ types unaware of QML as
146much as possible. This can be achieved by "pushing" references to C++ types
147into QML.
148
149This can be done by using \l {Required properties}{required properties} and
150setting them via \l QQmlApplicationEngine::setInitialProperties. It is also
151possible to create one or multiple \l {QML_SINGLETON}{singletons} which will
152return all the data the C++ side wants to provide to QML.
153
154With this approach, the C++ remains unchanged in the event that the QML needs
155to be refactored in the future.
156
157For a quick guide to choosing the correct approach to expose C++ types to QML,
158see \l {Choosing the Correct Integration Method Between C++ and QML}.
159
160\section2 Related Information
161\list
162\li \l{Writing QML Extensions with C++}
163 {Writing QML Extensions with C++ Tutorial}
164\li \l{Qt Quick Controls - Chat Tutorial}{Chat application tutorial}
165\endlist
166
167\section1 Using Qt Design Studio
168
169Qt Design Studio uses UI files that have the filename extension \e {.ui.qml}
170to separate the visual parts of the UI from the UI logic you implement in
171\e {.qml} files. You should edit UI files only in the \uicontrol {2D} view in
172Qt Design Studio. If you use some other tool to add code that Qt Design Studio
173does not support, it displays error messages. Fix the errors to enable visual
174editing of the UI files again. Typically, you should move the unsupported code
175to a \e {.qml} file.
176
177\section2 Related Information
178
179\list
180 \li \l{Qt Design Studio: UI Files}
181\endlist
182
183\section1 Using Qt Quick Layouts
184
185Qt offers Qt Quick Layouts to arrange Qt Quick items visually in a layout.
186Unlike its alternative, the item positioners, the Qt Quick Layouts can also
187resize its children on window resize. Although Qt Quick Layouts are often
188the desired choice for most use cases, the following \e dos and \e{don'ts}
189must be considered while using them:
190
191\section2 Dos
192
193\list
194 \li Use \l {Item::}{anchors} or the \l {Item::}{width} and \l {Item::}{height}
195 properties to specify the size of the layout against its non-layout parent
196 item.
197 \li Use the \l Layout attached property to set the size and alignment
198 attributes of the layout's immediate children.
199\endlist
200
201\section2 Don'ts
202
203\list
204 \li Do not define preferred sizes for items that provide implicitWidth and
205 implicitHeight, unless their implicit sizes are not satisfactory.
206 \li Do not use anchors on an item that is an immediate child of a layout.
207 Instead, use \c Layout.preferredWidth and \c Layout.preferredHeight:
208
209 \snippet qml/windowconstraints.qml rowlayout
210\endlist
211
212\note Layouts and anchors are both types of objects that take more memory and
213instantiation time. Avoid using them (especially in list and table delegates,
214and styles for controls) when simple bindings to x, y, width, and height
215properties are enough.
216
217\section2 Related Information
218
219\list
220 \li \l{Item Positioners}
221 \li \l{Qt Quick Layouts Overview}
222\endlist
223
224\section1 Type Safety
225
226When declaring properties in QML, it's easy and convenient to use the "var" type:
227
228\code
229property var name
230property var size
231property var optionsMenu
232\endcode
233
234However, this approach has several disadvantages:
235\list
236 \li If a value with the wrong type is assigned, the error reported will point
237 to the location of the property declaration, as opposed to the location
238 where the property was assigned to. This slows down the development
239 process by making it more difficult to track down errors.
240 \li Static anaylsis to catch errors like the ones mentioned above is not
241 possible.
242 \li The actual underlying type of the property is not always immediately clear
243 to the reader.
244\endlist
245
246Instead, always use the actual type where possible:
247
248\code
249property string name
250property int size
251property MyMenu optionsMenu
252\endcode
253
254\section1 Performance
255
256For information on performance in QML and Qt Quick,
257see \l {QML Performance Considerations And Suggestions}.
258
259\section1 Prefer Declarative Bindings Over Imperative Assignments
260
261In QML, it's possible to use imperative JavaScript code to perform tasks
262such as responding to input events, send data over a network, and so on.
263Imperative code has an important place in QML, but it's also important
264to be aware of when not to use it.
265
266For example, consider the following imperative assignment:
267
268\code
269Rectangle {
270 Component.onCompleted: color = "red"
271}
272\endcode
273
274This has the following disadvantages:
275
276\list
277\li It's slow. The color property will first be evaluated with a
278 default-constructed value, and then again with "red" later on.
279\li It delays errors that could be found at build time to run time, slowing
280 down the development process.
281\li It overwrites any declarative binding that was in place. In most cases this
282 is intended, but sometimes it can be unintentional.
283 See \l {Debugging overwriting of bindings} for more information.
284\li It interferes with tooling; Qt Quick Designer, for example, doesn't support
285 JavaScript.
286\endlist
287
288The code can be rewritten to be a declarative binding instead:
289
290\code
291Rectangle {
292 color: "red"
293}
294\endcode
295
296\section1 Tools and Utilities
297
298For information on useful tools and utilies that make working with QML and
299Qt Quick easier, see \l {Qt Quick Tools and Utilities}.
300
301\section1 Scene Graph
302
303For information on Qt Quick's scene graph, see \l {Qt Quick Scene Graph}.
304
305\section1 Scalable User Interfaces
306
307As display resolutions improve, a scalable application UI becomes more and
308more important. One of the approaches to achieve this is to maintain several
309copies of the UI for different screen resolutions, and load the appropriate one
310depending on the available resolution. Although this works pretty
311well, it adds to the maintenance overhead.
312
313Qt offers a better solution to this problem and recommends the application
314developers to follow these tips:
315
316\list
317 \li Use anchors or the Qt Quick Layouts module to lay out the visual items.
318 \li Do not specify explicit width and height for a visual item.
319 \li Provide UI resources such as images and icons for each display resolution
320 that your application supports. The Qt Quick Controls gallery example
321 demonstrates this well by providing the \c qt-logo.png for \c @2x, \c @3x,
322 and \c @4x resolutions, enabling the application to cater to high
323 resolution displays. Qt automatically chooses the appropriate
324 image that is suitable for the given display, provided the high DPI scaling
325 feature is explicitly enabled.
326 \li Use SVG images for small icons. While larger SVGs can be slow to render,
327 small ones work well. Vector images avoid the need to provide several
328 versions of an image, as is necessary with bitmap images.
329 \li Use font-based icons, such as Font Awesome. These scale to any display
330 resolution, and also allow colorization. The
331 Qt Quick Controls Text Editor example demonstrates this well.
332\endlist
333
334With this in place, your application's UI should scale depending
335on the display resolution on offer.
336
337\image qtquickcontrols-gallery-welcome.png
338
339\section2 Related Information
340
341\list
342 \li \l{Qt Quick Controls - Gallery}{Gallery example}
343 \li \l{Qt Quick Controls - Text Editor}{Text Editor example}
344 \li \l{Font Awesome}
345 \li \l{Scalability}
346 \li \l{High DPI}
347\endlist
348*/