Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
advtutorial.qdoc
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\page qml-advtutorial.html
6\title QML Advanced Tutorial
7\brief A more advanced tutorial, showing how to use QML to create a game.
8\nextpage QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
9
10This tutorial walks step-by-step through the creation of a full application using QML.
11It assumes that you already know the basics of QML (for example, from reading the
12\l{QML Tutorial}{simple tutorial}).
13
14In this tutorial we write a game, \e {Same Game}, based on the Same Game application
15included in the declarative \c examples directory, which looks like this:
16
17\image declarative-samegame.png
18 {SameGame with colored blocks, New Game button, and score display}
19
20We will cover concepts for producing a fully functioning application, including
21JavaScript integration, using QML \l{State}{Qt Quick States} and \l{Behavior}{Behaviors} to
22manage components and enhance your interface, and storing persistent application data.
23
24An understanding of JavaScript is helpful to understand parts of this tutorial, but if you don't
25know JavaScript you can still get a feel for how you can integrate backend logic to create and
26control QML types.
27
28
29Tutorial chapters:
30
31\list 1
32\li \l {QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks}{Creating the Game Canvas and Blocks}
33\li \l {QML Advanced Tutorial 2 - Populating the Game Canvas}{Populating the Game Canvas}
34\li \l {QML Advanced Tutorial 3 - Implementing the Game Logic}{Implementing the Game Logic}
35\li \l {QML Advanced Tutorial 4 - Finishing Touches}{Finishing Touches}
36\endlist
37
38All the code in this tutorial can be found in Qt's \c examples/quick/tutorials/samegame
39directory.
40*/
41
42/*!
43\title QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
44\previouspage QML Advanced Tutorial
45\nextpage QML Advanced Tutorial 2 - Populating the Game Canvas
46
47\example tutorials/samegame/samegame1
48
49\section2 Creating the Application Screen
50
51The first step is to create the basic QML items in your application.
52
53To begin with, we create our Same Game application with a main screen like this:
54
55\image declarative-adv-tutorial1.png
56 {Empty game canvas with New Game button and score placeholder}
57
58This is defined by the main application file, \c samegame.qml, which looks like this:
59
60\snippet tutorials/samegame/samegame1/samegame.qml 0
61
62This gives you a basic game window that includes the main canvas for the
63blocks, a "New Game" button and a score display.
64
65One item you may not recognize here
66is the \l SystemPalette item. This provides access to the Qt system palette
67and is used to give the button a more native look-and-feel.
68
69Notice the anchors for the \c Item, \c Button and \c Text types are set using
70group (dot) notation for readability.
71
72\section2 Adding \c Button and \c Block Components
73
74The \c Button item in the code above is defined in a separate component file named \c Button.qml.
75To create a functional button, we use the QML types \l Text and \l MouseArea inside a \l Rectangle.
76Here is the \c Button.qml code:
77
78\snippet tutorials/samegame/samegame1/Button.qml 0
79
80This essentially defines a rectangle that contains text and can be clicked. The \l MouseArea
81has an \c onClicked() handler that is implemented to emit the \c clicked() signal of the
82\c container when the area is clicked.
83
84In Same Game, the screen is filled with small blocks when the game begins.
85Each block is just an item that contains an image. The block
86code is defined in a separate \c Block.qml file:
87
88\snippet tutorials/samegame/samegame1/Block.qml 0
89
90At the moment, the block doesn't do anything; it is just an image. As the
91tutorial progresses we will animate and give behaviors to the blocks.
92We have not added any code yet to create the blocks; we will do this
93in the next chapter.
94
95We have set the image to be the size of its parent Item using \c {anchors.fill: parent}.
96This means that when we dynamically create and resize the block items
97later on in the tutorial, the image will be scaled automatically to the
98correct size.
99
100Notice the relative path for the Image type's \c source property.
101This path is relative to the location of the file that contains the \l Image type.
102Alternatively, you could set the Image source to an absolute file path or a URL
103that contains an image.
104
105You should be familiar with the code so far. We have just created some basic
106types to get started. Next, we will populate the game canvas with some blocks.
107*/
108
109
110/*!
111\title QML Advanced Tutorial 2 - Populating the Game Canvas
112\previouspage QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
113\nextpage QML Advanced Tutorial 3 - Implementing the Game Logic
114
115\example tutorials/samegame/samegame2
116
117\section2 Generating the Blocks in JavaScript
118
119Now that we've written some types, let's start writing the game.
120
121The first task is to generate the game blocks. Each time the New Game button
122is clicked, the game canvas is populated with a new, random set of
123blocks. Since we need to dynamically generate new blocks for each new game,
124we cannot use \l Repeater to define the blocks. Instead, we will
125create the blocks in JavaScript.
126
127Here is the JavaScript code for generating the blocks, contained in a new
128file, \c samegame.js. The code is explained below.
129
130\snippet tutorials/samegame/samegame2/samegame.js 0
131
132The \c startNewGame() function deletes the blocks created in the previous game and
133calculates the number of rows and columns of blocks required to fill the game window for the new game.
134Then, it creates an array to store all the game
135blocks, and calls \c createBlock() to create enough blocks to fill the game window.
136
137The \c createBlock() function creates a block from the \c Block.qml file
138and moves the new block to its position on the game canvas. This involves several steps:
139
140\list
141
142\li \l {QtQml::Qt::createComponent()}{Qt.createComponent()} is called to
143 generate a type from \c Block.qml. If the component is ready,
144 we can call \c createObject() to create an instance of the \c Block
145 item.
146
147\li If \c createObject() returned null (i.e. if there was an error
148 while loading the object), print the error information.
149
150\li Place the block in its position on the board and set its width and
151 height. Also, store it in the blocks array for future reference.
152
153\li Finally, print error information to the console if the component
154 could not be loaded for some reason (for example, if the file is
155 missing).
156
157\endlist
158
159
160\section2 Connecting JavaScript Components to QML
161
162Now we need to call the JavaScript code in \c samegame.js from our QML files.
163To do this, we add this line to \c samegame.qml which imports
164the JavaScript file as a \l{QML Modules}{module}:
165
166\snippet tutorials/samegame/samegame2/samegame.qml 2
167
168This allows us to refer to any functions within \c samegame.js using "SameGame"
169as a prefix: for example, \c SameGame.startNewGame() or \c SameGame.createBlock().
170This means we can now connect the New Game button's \c onClicked handler to the \c startNewGame()
171function, like this:
172
173\snippet tutorials/samegame/samegame2/samegame.qml 1
174
175So, when you click the New Game button, \c startNewGame() is called and generates a field of blocks, like this:
176
177\image declarative-adv-tutorial2.png
178 {Game canvas populated with a grid of blocks}
179
180Now, we have a screen of blocks, and we can begin to add the game mechanics.
181
182*/
183
184/*!
185\title QML Advanced Tutorial 3 - Implementing the Game Logic
186\previouspage QML Advanced Tutorial 2 - Populating the Game Canvas
187\nextpage QML Advanced Tutorial 4 - Finishing Touches
188
189\example tutorials/samegame/samegame3
190
191\section2 Making a Playable Game
192
193Now that we have all the game components, we can add the game logic that
194dictates how a player interacts with the blocks and plays the game
195until it is won or lost.
196
197To do this, we have added the following functions to \c samegame.js:
198
199\list
200\li \c{handleClick(x,y)}
201\li \c{floodFill(xIdx,yIdx,type)}
202\li \c{shuffleDown()}
203\li \c{victoryCheck()}
204\li \c{floodMoveCheck(xIdx, yIdx, type)}
205\endlist
206
207As this is a tutorial about QML, not game design, we will only discuss \c handleClick() and \c victoryCheck() below since they interface directly with the QML types. Note that although the game logic here is written in JavaScript, it could have been written in C++ and then exposed to QML.
208
209\section3 Enabling Mouse Click Interaction
210
211To make it easier for the JavaScript code to interface with the QML types, we have added an Item called \c gameCanvas to \c samegame.qml. It replaces the background as the item which contains the blocks. It also accepts mouse input from the user. Here is the item code:
212
213\snippet tutorials/samegame/samegame3/samegame.qml 1
214
215The \c gameCanvas item is the exact size of the board, and has a \c score property and a \l MouseArea to handle mouse clicks.
216The blocks are now created as its children, and its dimensions are used to determine the board size so that
217the application scales to the available screen size.
218Since its size is bound to a multiple of \c blockSize, \c blockSize was moved out of \c samegame.js and into \c samegame.qml as a QML property.
219Note that it can still be accessed from the script.
220
221When clicked, the \l MouseArea calls \c{handleClick()} in \c samegame.js, which determines whether the player's click should cause any blocks to be removed, and updates \c gameCanvas.score with the current score if necessary. Here is the \c handleClick() function:
222
223\snippet tutorials/samegame/samegame3/samegame.js 1
224
225Note that if \c score was a global variable in the \c{samegame.js} file you would not be able to bind to it. You can only bind to QML properties.
226
227\section3 Updating the Score
228
229When the player clicks a block and triggers \c handleClick(), \c handleClick() also calls \c victoryCheck() to update the score and to check whether the player has completed the game. Here is the \c victoryCheck() code:
230
231\snippet tutorials/samegame/samegame3/samegame.js 2
232
233This updates the \c gameCanvas.score value and displays a "Game Over" dialog if the game is finished.
234
235The Game Over dialog is created using a \c Dialog type that is defined in \c Dialog.qml. Here is the \c Dialog.qml code. Notice how it is designed to be usable imperatively from the script file, via the functions and signals:
236
237\snippet tutorials/samegame/samegame3/Dialog.qml 0
238
239And this is how it is used in the main \c samegame.qml file:
240
241\snippet tutorials/samegame/samegame3/samegame.qml 2
242
243We give the dialog a \l {Item::z}{z} value of 100 to ensure it is displayed on top of our other components. The default \c z value for an item is 0.
244
245
246\section3 A Dash of Color
247
248It's not much fun to play Same Game if all the blocks are the same color, so we've modified the \c createBlock() function in \c samegame.js to randomly create a different type of block (for either red, green or blue) each time it is called. \c Block.qml has also changed so that each block contains a different image depending on its type:
249
250\snippet tutorials/samegame/samegame3/Block.qml 0
251
252
253\section2 A Working Game
254
255Now we now have a working game! The blocks can be clicked, the player can score, and the game can end (and then you can start a new one).
256Here is a screenshot of what has been accomplished so far:
257
258\image declarative-adv-tutorial3.png
259 {Working game with colored blocks partially cleared}
260
261This is what \c samegame.qml looks like now:
262
263\snippet tutorials/samegame/samegame3/samegame.qml 0
264
265The game works, but it's a little boring right now. Where are the smooth animated transitions? Where are the high scores?
266If you were a QML expert you could have written these in the first iteration, but in this tutorial they've been saved
267until the next chapter - where your application becomes alive!
268
269*/
270
271/*!
272\title QML Advanced Tutorial 4 - Finishing Touches
273\previouspage QML Advanced Tutorial 3 - Implementing the Game Logic
274
275\example tutorials/samegame/samegame4
276
277\section2 Adding Some Flair
278
279Now we're going to do two things to liven up the game: animate the blocks and add a High Score system.
280
281In anticipation of the new block animations, \c Block.qml file is now renamed to \c BoomBlock.qml.
282
283\section3 Animating Block Movement
284
285First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid
286movement, and in this case we're going to use the \l Behavior type to add a \l SpringAnimation.
287In \c BoomBlock.qml, we apply a \l SpringAnimation behavior to the \c x and \c y properties so that the
288block will follow and animate its movement in a spring-like fashion towards the specified position (whose
289values will be set by \c samegame.js).Here is the code added to \c BoomBlock.qml:
290
291\snippet tutorials/samegame/samegame4/BoomBlock.qml 1
292
293The \c spring and \c damping values can be changed to modify the spring-like effect of the animation.
294
295The \c {enabled: spawned} setting refers to the \c spawned value that is set from \c createBlock() in \c samegame.js.
296This ensures the \l SpringAnimation on the \c x is only enabled after \c createBlock() has set the block to
297the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling
298from the top in rows. (Try commenting out \c {enabled: spawned} and see for yourself.)
299
300\section3 Animating Block Opacity Changes
301
302Next, we will add a smooth exit animation. For this, we'll use a \l Behavior type, which allows us to specify
303a default animation when a property change occurs. In this case, when the \c opacity of a Block changes, we will
304animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully
305visible and invisible. To do this, we'll apply a \l Behavior on the \c opacity property of the \c Image
306type in \c BoomBlock.qml:
307
308\snippet tutorials/samegame/samegame4/BoomBlock.qml 2
309
310Note the \c{opacity: 0} which means the block is transparent when it is first created. We could set the opacity
311in \c samegame.js when we create and destroy the blocks,
312but instead we'll use \l{Qt Quick States}{states}, since this is useful for the next animation we're going to add.
313Initially, we add these States to the root type of \c{BoomBlock.qml}:
314\code
315 property bool dying: false
316 states: [
317 State{ name: "AliveState"; when: spawned == true && dying == false
318 PropertyChanges { target: img; opacity: 1 }
319 },
320 State{ name: "DeathState"; when: dying == true
321 PropertyChanges { target: img; opacity: 0 }
322 }
323 ]
324\endcode
325
326Now blocks will automatically fade in, as we already set \c spawned to true when we implemented the block animations.
327To fade out, we set \c dying to true instead of setting opacity to 0 when a block is destroyed (in the \c floodFill() function).
328
329\section3 Adding Particle Effects
330
331Finally, we'll add a cool-looking particle effect to the blocks when they are destroyed. To do this, we first add a \l ParticleSystem in
332\c BoomBlock.qml, like so:
333
334\snippet tutorials/samegame/samegame4/BoomBlock.qml 3
335
336To fully understand this you should read \l {Using the Qt Quick Particle System}, but it's important to note that \c emitRate is set
337to zero so that particles are not emitted normally.
338Also, we extend the \c dying State, which creates a burst of particles by calling the \c burst() method on the particles type. The code for the states now look
339like this:
340
341\snippet tutorials/samegame/samegame4/BoomBlock.qml 4
342
343Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the
344player's actions. The end result is shown below, with a different set of images to demonstrate basic theming:
345
346\image declarative-adv-tutorial4.gif
347 {Game demonstrating smooth block animations}
348
349The theme change here is produced simply by replacing the block images. This can be done at runtime by changing the \l Image \c source property, so for a further challenge, you could add a button that toggles between themes with different images.
350
351\section2 Keeping a High Scores Table
352
353Another feature we might want to add to the game is a method of storing and retrieving high scores.
354
355To do this, we will show a dialog when the game is over to request the player's name and add it to a High Scores table.
356This requires a few changes to \c Dialog.qml. In addition to a \c Text type, it now has a
357\c TextInput child item for receiving keyboard text input:
358
359\snippet tutorials/samegame/samegame4/Dialog.qml 0
360\dots 4
361\snippet tutorials/samegame/samegame4/Dialog.qml 2
362\dots 4
363\snippet tutorials/samegame/samegame4/Dialog.qml 3
364
365We'll also add a \c showWithInput() function. The text input will only be visible if this function
366is called instead of \c show(). When the dialog is closed, it emits a \c closed() signal, and
367other types can retrieve the text entered by the user through an \c inputText property:
368
369\snippet tutorials/samegame/samegame4/Dialog.qml 0
370\snippet tutorials/samegame/samegame4/Dialog.qml 1
371\dots 4
372\snippet tutorials/samegame/samegame4/Dialog.qml 3
373
374Now the dialog can be used in \c samegame.qml:
375
376\snippet tutorials/samegame/samegame4/samegame.qml 0
377
378When the dialog emits the \c closed signal, we call the new \c saveHighScore() function in \c samegame.js, which stores the high score locally in an SQL database and also send the score to an online database if possible.
379
380The \c nameInputDialog is activated in the \c victoryCheck() function in \c samegame.js:
381
382\snippet tutorials/samegame/samegame4/samegame.js 3
383\dots 4
384\snippet tutorials/samegame/samegame4/samegame.js 4
385
386\section3 Storing High Scores Offline
387
388Now we need to implement the functionality to actually save the High Scores table.
389
390Here is the \c saveHighScore() function in \c samegame.js:
391
392\snippet tutorials/samegame/samegame4/samegame.js 2
393
394First we call \c sendHighScore() (explained in the section below) if it is possible to send the high scores to an online database.
395
396Then, we use the \l{QtQuick.LocalStorage}{Local Storage API} to maintain a persistent SQL database unique to this application. We create an offline storage database for the high scores using \c openDatabaseSync() and prepare the data and SQL query that we want to use to save it. The offline storage API uses SQL queries for data manipulation and retrieval, and in the \c db.transaction() call we use three SQL queries to initialize the database (if necessary), and then add to and retrieve high scores. To use the returned data, we turn it into a string with one line per row returned, and show a dialog containing that string.
397
398This is one way of storing and displaying high scores locally, but certainly not the only way. A more complex alternative would be to create a high score dialog component, and pass it the results for processing and display (instead of reusing the \c Dialog). This would allow a more themeable dialog that could better present the high scores. If your QML is the UI for a C++ application, you could also have passed the score to a C++ function to store it locally in a variety of ways, including a simple format without SQL or in another SQL database.
399
400\section3 Storing High Scores Online
401
402You've seen how you can store high scores locally, but it is also easy to integrate a web-enabled high score storage into your QML application. The implementation we've done her is very
403simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and
404displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores,
405but that's beyond the scope of this tutorial. The php script we use here is available in the \c examples directory.
406
407If the player entered their name we can send the data to the web service us
408
409If the player enters a name, we send the data to the service using this code in \c samegame.js:
410
411\snippet tutorials/samegame/samegame4/samegame.js 1
412
413The \l{The XMLHttpRequest JavaScript Object}{XMLHttpRequest} in this code is the same as the \c XMLHttpRequest() as you'll find in standard browser JavaScript, and can be used in the same way to dynamically get XML
414or QML from the web service to display the high scores. We don't worry about the response in this case - we just post the high
415score data to the web server. If it had returned a QML file (or a URL to a QML file) you could instantiate it in much the same
416way as you did with the blocks.
417
418An alternate way to access and submit web-based data would be to use QML types designed for this purpose. XmlListModel
419makes it very easy to fetch and display XML based data such as RSS in a QML application.
420
421
422\section2 That's It!
423
424By following this tutorial you've seen how you can write a fully functional application in QML:
425
426\list
427\li Build your application with \l {Qt Quick QML Types}{QML types}
428\li Add application logic \l{JavaScript Expressions in QML Documents}{with JavaScript code}
429\li Add animations with \l {Behavior}{Behaviors} and \l{Qt Quick States}{states}
430\li Store persistent application data using, for example, \l QtQuick.LocalStorage or \l{The XMLHttpRequest JavaScript Object}{XMLHttpRequest}
431\endlist
432
433There is so much more to learn about QML that we haven't been able to cover in this tutorial. Check out all the
434examples and the \l {Qt Quick}{documentation} to see all the things you can do with QML!
435*/