Sophie

Sophie

distrib > Mageia > 7 > i586 > media > core-updates > by-pkgid > 6e2327ca1c896c6d674ae53117299f21 > files > 1817

qtdeclarative5-doc-5.12.6-1.mga7.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- advtutorial.qdoc -->
  <title>QML Advanced Tutorial 4 - Finishing Touches | Qt Quick 5.12.6</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.12</td><td ><a href="qtquick-index.html">Qt Quick</a></td><td >QML Advanced Tutorial 4 - Finishing Touches</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right"><a href="qtquick-index.html">Qt 5.12.6 Reference Documentation</a></td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
  <link rel="prev" href="qtquick-tutorials-samegame-samegame3-example.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="qtquick-tutorials-samegame-samegame3-example.html">QML Advanced Tutorial 3 - Implementing the Game Logic</a>
</p><p/>
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level2"><a href="#adding-some-flair">Adding Some Flair</a></li>
<li class="level2"><a href="#keeping-a-high-scores-table">Keeping a High Scores Table</a></li>
<li class="level2"><a href="#that-s-it">That's It!</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">QML Advanced Tutorial 4 - Finishing Touches</h1>
<span class="subtitle"></span>
<!-- $$$tutorials/samegame/samegame4-description -->
<div class="descr"> <a name="details"></a>
<a name="adding-some-flair"></a>
<h3 id="adding-some-flair">Adding Some Flair</h3>
<p>Now we're going to do two things to liven up the game: animate the blocks and add a High Score system.</p>
<p>We've also cleaned up the directory structure for our application files. We now have a lot of files, so all the JavaScript and QML files outside of <code>samegame.qml</code> have been moved into a new sub-directory named &quot;content&quot;.</p>
<p>In anticipation of the new block animations, <code>Block.qml</code> file is now renamed to <code>BoomBlock.qml</code>.</p>
<a name="animating-block-movement"></a>
<h4 id="animating-block-movement">Animating Block Movement</h4>
<p>First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid movement, and in this case we're going to use the <a href="qml-qtquick-behavior.html">Behavior</a> type to add a <a href="qml-qtquick-springanimation.html">SpringAnimation</a>. In <code>BoomBlock.qml</code>, we apply a <a href="qml-qtquick-springanimation.html">SpringAnimation</a> behavior to the <code>x</code> and <code>y</code> properties so that the block will follow and animate its movement in a spring-like fashion towards the specified position (whose values will be set by <code>samegame.js</code>).Here is the code added to <code>BoomBlock.qml</code>:</p>
<pre class="qml">

  property bool spawned: false

  Behavior on x {
      enabled: spawned;
      SpringAnimation{ spring: 2; damping: 0.2 }
  }
  Behavior on y {
      SpringAnimation{ spring: 2; damping: 0.2 }
  }

</pre>
<p>The <code>spring</code> and <code>damping</code> values can be changed to modify the spring-like effect of the animation.</p>
<p>The <code>enabled: spawned</code> setting refers to the <code>spawned</code> value that is set from <code>createBlock()</code> in <code>samegame.js</code>. This ensures the <a href="qml-qtquick-springanimation.html">SpringAnimation</a> on the <code>x</code> is only enabled after <code>createBlock()</code> has set the block to the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling from the top in rows. (Try commenting out <code>enabled: spawned</code> and see for yourself.)</p>
<a name="animating-block-opacity-changes"></a>
<h4 id="animating-block-opacity-changes">Animating Block Opacity Changes</h4>
<p>Next, we will add a smooth exit animation. For this, we'll use a <a href="qml-qtquick-behavior.html">Behavior</a> type, which allows us to specify a default animation when a property change occurs. In this case, when the <code>opacity</code> of a Block changes, we will animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully visible and invisible. To do this, we'll apply a <a href="qml-qtquick-behavior.html">Behavior</a> on the <code>opacity</code> property of the <code>Image</code> type in <code>BoomBlock.qml</code>:</p>
<pre class="qml">

  Image {
      id: img

      anchors.fill: parent
      source: {
          if (type == 0)
              return "../../shared/pics/redStone.png";
          else if (type == 1)
              return "../../shared/pics/blueStone.png";
          else
              return "../../shared/pics/greenStone.png";
      }
      opacity: 0

      Behavior on opacity {
          NumberAnimation { properties:"opacity"; duration: 200 }
      }
  }

</pre>
<p>Note the <code>opacity: 0</code> which means the block is transparent when it is first created. We could set the opacity in <code>samegame.js</code> when we create and destroy the blocks, but instead we'll use <a href="qtquick-statesanimations-states.html">states</a>, since this is useful for the next animation we're going to add. Initially, we add these States to the root type of <code>BoomBlock.qml</code>:</p>
<pre class="cpp">

  property bool dying: <span class="keyword">false</span>
  states: <span class="operator">[</span>
      State{ name: <span class="string">&quot;AliveState&quot;</span>; when: spawned <span class="operator">=</span><span class="operator">=</span> <span class="keyword">true</span> <span class="operator">&amp;</span><span class="operator">&amp;</span> dying <span class="operator">=</span><span class="operator">=</span> <span class="keyword">false</span>
          PropertyChanges { target: img; opacity: <span class="number">1</span> }
      }<span class="operator">,</span>
      State{ name: <span class="string">&quot;DeathState&quot;</span>; when: dying <span class="operator">=</span><span class="operator">=</span> <span class="keyword">true</span>
          PropertyChanges { target: img; opacity: <span class="number">0</span> }
      }
  <span class="operator">]</span>

</pre>
<p>Now blocks will automatically fade in, as we already set <code>spawned</code> to true when we implemented the block animations. To fade out, we set <code>dying</code> to true instead of setting opacity to 0 when a block is destroyed (in the <code>floodFill()</code> function).</p>
<a name="adding-particle-effects"></a>
<h4 id="adding-particle-effects">Adding Particle Effects</h4>
<p>Finally, we'll add a cool-looking particle effect to the blocks when they are destroyed. To do this, we first add a <a href="qml-qtquick-particles-particlesystem.html">ParticleSystem</a> in <code>BoomBlock.qml</code>, like so:</p>
<pre class="qml">

  ParticleSystem {
      id: sys
      anchors.centerIn: parent
      ImageParticle {
          // ![0]
          source: {
              if (type == 0)
                  return "../../shared/pics/redStar.png";
              else if (type == 1)
                  return "../../shared/pics/blueStar.png";
              else
                  return "../../shared/pics/greenStar.png";
          }
          rotationVelocityVariation: 360
          // ![0]
      }

      Emitter {
          id: particles
          anchors.centerIn: parent
          emitRate: 0
          lifeSpan: 700
          velocity: AngleDirection {angleVariation: 360; magnitude: 80; magnitudeVariation: 40}
          size: 16
      }
  }

</pre>
<p>To fully understand this you should read <a href="qtquick-effects-particles.html">Using the Qt Quick Particle System</a>, but it's important to note that <code>emitRate</code> is set to zero so that particles are not emitted normally. Also, we extend the <code>dying</code> State, which creates a burst of particles by calling the <code>burst()</code> method on the particles type. The code for the states now look like this:</p>
<pre class="qml">

  states: [
      State {
          name: "AliveState"
          when: spawned == true && dying == false
          PropertyChanges { target: img; opacity: 1 }
      },

      State {
          name: "DeathState"
          when: dying == true
          StateChangeScript { script: particles.burst(50); }
          PropertyChanges { target: img; opacity: 0 }
          StateChangeScript { script: block.destroy(1000); }
      }
  ]

</pre>
<p>Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the player's actions. The end result is shown below, with a different set of images to demonstrate basic theming:</p>
<p class="centerAlign"><img src="images/declarative-adv-tutorial4.gif" alt="" /></p><p>The theme change here is produced simply by replacing the block images. This can be done at runtime by changing the <a href="qml-qtquick-image.html">Image</a> <code>source</code> property, so for a further challenge, you could add a button that toggles between themes with different images.</p>
<a name="keeping-a-high-scores-table"></a>
<h3 id="keeping-a-high-scores-table">Keeping a High Scores Table</h3>
<p>Another feature we might want to add to the game is a method of storing and retrieving high scores.</p>
<p>To 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. This requires a few changes to <code>Dialog.qml</code>. In addition to a <code>Text</code> type, it now has a <code>TextInput</code> child item for receiving keyboard text input:</p>
<pre class="qml">

  Rectangle {
      id: container
      ...
      TextInput {
          id: textInput
          anchors { verticalCenter: parent.verticalCenter; left: dialogText.right }
          width: 80
          text: ""

          onAccepted: container.hide()    // close dialog when Enter is pressed
      }
      ...
  }

</pre>
<p>We'll also add a <code>showWithInput()</code> function. The text input will only be visible if this function is called instead of <code>show()</code>. When the dialog is closed, it emits a <code>closed()</code> signal, and other types can retrieve the text entered by the user through an <code>inputText</code> property:</p>
<pre class="qml">

  Rectangle {
      id: container
      property string inputText: textInput.text
      signal closed

      function show(text) {
          dialogText.text = text;
          container.opacity = 1;
          textInput.opacity = 0;
      }

      function showWithInput(text) {
          show(text);
          textInput.opacity = 1;
          textInput.focus = true;
          textInput.text = ""
      }

      function hide() {
          textInput.focus = false;
          container.opacity = 0;
          container.closed();
      }
      ...
  }

</pre>
<p>Now the dialog can be used in <code>samegame.qml</code>:</p>
<pre class="qml">

  Dialog {
      id: nameInputDialog
      anchors.centerIn: parent
      z: 100

      onClosed: {
          if (nameInputDialog.inputText != "")
              SameGame.saveHighScore(nameInputDialog.inputText);
      }
  }

</pre>
<p>When the dialog emits the <code>closed</code> signal, we call the new <code>saveHighScore()</code> function in <code>samegame.js</code>, which stores the high score locally in an SQL database and also send the score to an online database if possible.</p>
<p>The <code>nameInputDialog</code> is activated in the <code>victoryCheck()</code> function in <code>samegame.js</code>:</p>
<pre class="js">

  function victoryCheck() {
      ...
      //Check whether game has finished
      if (deservesBonus || !(floodMoveCheck(0, maxRow - 1, -1))) {
          gameDuration = new Date() - gameDuration;
          nameInputDialog.showWithInput("You won! Please enter your name: ");
      }
  }

</pre>
<a name="storing-high-scores-offline"></a>
<h4 id="storing-high-scores-offline">Storing High Scores Offline</h4>
<p>Now we need to implement the functionality to actually save the High Scores table.</p>
<p>Here is the <code>saveHighScore()</code> function in <code>samegame.js</code>:</p>
<pre class="js">

  function saveHighScore(name) {
      if (scoresURL != "")
          sendHighScore(name);

      var db = Sql.LocalStorage.openDatabaseSync("SameGameScores", "1.0", "Local SameGame High Scores", 100);
      var dataStr = "INSERT INTO Scores VALUES(?, ?, ?, ?)";
      var data = [name, gameCanvas.score, maxColumn + "x" + maxRow, Math.floor(gameDuration / 1000)];
      db.transaction(function(tx) {
          tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(name TEXT, score NUMBER, gridSize TEXT, time NUMBER)');
          tx.executeSql(dataStr, data);

          var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "12x17" ORDER BY score desc LIMIT 10');
          var r = "\nHIGH SCORES for a standard sized grid\n\n"
          for (var i = 0; i < rs.rows.length; i++) {
              r += (i + 1) + ". " + rs.rows.item(i).name + ' got ' + rs.rows.item(i).score + ' points in ' + rs.rows.item(i).time + ' seconds.\n';
          }
          dialog.show(r);
      });
  }

</pre>
<p>First we call <code>sendHighScore()</code> (explained in the section below) if it is possible to send the high scores to an online database.</p>
<p>Then, we use the <a href="qtquick-localstorage-qmlmodule.html">Local Storage API</a> to maintain a persistent SQL database unique to this application. We create an offline storage database for the high scores using <code>openDatabaseSync()</code> 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 <code>db.transaction()</code> 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.</p>
<p>This 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 <code>Dialog</code>). 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.</p>
<a name="storing-high-scores-online"></a>
<h4 id="storing-high-scores-online">Storing High Scores Online</h4>
<p>You'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 simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores, but that's beyond the scope of this tutorial. The php script we use here is available in the <code>examples</code> directory.</p>
<p>If the player entered their name we can send the data to the web service us</p>
<p>If the player enters a name, we send the data to the service using this code in <code>samegame.js</code>:</p>
<pre class="js">

  function sendHighScore(name) {
      var postman = new XMLHttpRequest()
          var postData = "name=" + name + "&score=" + gameCanvas.score + "&gridSize=" + maxColumn + "x" + maxRow + "&time=" + Math.floor(gameDuration / 1000);
      postman.open("POST", scoresURL, true);
      postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      postman.onreadystatechange = function() {
          if (postman.readyState == postman.DONE) {
              dialog.show("Your score has been uploaded.");
          }
      }
      postman.send(postData);
  }

</pre>
<p>The XMLHttpRequest in this code is the same as the <code>XMLHttpRequest()</code> as you'll find in standard browser JavaScript, and can be used in the same way to dynamically get XML or 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 score 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 way as you did with the blocks.</p>
<p>An alternate way to access and submit web-based data would be to use QML types designed for this purpose. XmlListModel makes it very easy to fetch and display XML based data such as RSS in a QML application (see the Flickr demo for an example).</p>
<a name="that-s-it"></a>
<h3 id="that-s-it">That's It!</h3>
<p>By following this tutorial you've seen how you can write a fully functional application in QML:</p>
<ul>
<li>Build your application with <a href="qtquick-qmlmodule.html">QML types</a></li>
<li>Add application logic with JavaScript code</li>
<li>Add animations with <a href="qml-qtquick-behavior.html">Behaviors</a> and <a href="qtquick-statesanimations-states.html">states</a></li>
<li>Store persistent application data using, for example, <a href="qtquick-localstorage-qmlmodule.html">QtQuick.LocalStorage</a> or XMLHttpRequest</li>
</ul>
<p>There is so much more to learn about QML that we haven't been able to cover in this tutorial. Check out all the examples and the <a href="qtquick-index.html">documentation</a> to see all the things you can do with QML!</p>
<p>Files:</p>
<ul>
<li><a href="qtquick-tutorials-samegame-samegame4-content-boomblock-qml.html">tutorials/samegame/samegame4/content/BoomBlock.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-content-button-qml.html">tutorials/samegame/samegame4/content/Button.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-content-dialog-qml.html">tutorials/samegame/samegame4/content/Dialog.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-content-samegame-js.html">tutorials/samegame/samegame4/content/samegame.js</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-highscores-score-data-xml.html">tutorials/samegame/samegame4/highscores/score_data.xml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-samegame-qml.html">tutorials/samegame/samegame4/samegame.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame4-samegame4-qmlproject.html">tutorials/samegame/samegame4/samegame4.qmlproject</a></li>
</ul>
</div>
<!-- @@@tutorials/samegame/samegame4 -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="qtquick-tutorials-samegame-samegame3-example.html">QML Advanced Tutorial 3 - Implementing the Game Logic</a>
</p>
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2019 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>