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