Sophie

Sophie

distrib > Mageia > 6 > x86_64 > by-pkgid > 2cba8df17162abb32fcb8e6852f3eacc > files > 195

qtdeclarative5-doc-5.9.4-1.mga6.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" />
<!-- expressions.qdoc -->
  <title>JavaScript Expressions in QML Documents | Qt QML 5.9</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.9</td><td ><a href="qtqml-index.html">Qt QML</a></td><td >JavaScript Expressions in QML Documents</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.9.4 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#javascript-in-property-bindings">JavaScript in Property Bindings</a></li>
<li class="level1"><a href="#javascript-in-signal-handlers">JavaScript in Signal Handlers</a></li>
<li class="level1"><a href="#javascript-in-standalone-functions">JavaScript in Standalone Functions</a></li>
<li class="level2"><a href="#javascript-in-custom-object-methods">JavaScript in Custom Object Methods</a></li>
<li class="level2"><a href="#functions-in-imported-javascript-files">Functions in Imported JavaScript Files</a></li>
<li class="level2"><a href="#connecting-signals-to-javascript-functions">Connecting Signals to JavaScript Functions</a></li>
<li class="level1"><a href="#javascript-in-application-startup-code">JavaScript in Application Startup Code</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">JavaScript Expressions in QML Documents</h1>
<span class="subtitle"></span>
<!-- $$$qtqml-javascript-expressions.html-description -->
<div class="descr"> <a name="details"></a>
<p>The <a href="qtqml-javascript-hostenvironment.html">JavaScript Host Environment</a> provided by QML can run valid standard JavaScript constructs such as conditional operators, arrays, variable setting, loops. In addition to the standard JavaScript properties, the <a href="qtqml-javascript-qmlglobalobject.html">QML Global Object</a> includes a number of helper methods that simplify building UIs and interacting with the QML environment.</p>
<p>The JavaScript environment provided by QML is stricter than that in a web browser. For example, in QML you cannot add to, or modify, members of the JavaScript global object. In regular JavaScript, it is possible to do this accidentally by using a variable without declaring it. In QML this will throw an exception, so all local variables must be explicitly declared. See <a href="qtqml-javascript-hostenvironment.html#javascript-environment-restrictions">JavaScript Environment Restrictions</a> for a complete description of the restrictions on JavaScript code executed from QML.</p>
<p>Various parts of <a href="qtqml-documents-topic.html">QML documents</a> can contain JavaScript code:</p>
<ol class="1" type="1"><li>The body of <a href="qtqml-syntax-propertybinding.html">property bindings</a>. These JavaScript expressions describe relationships between QML object <a href="qtqml-syntax-objectattributes.html#property-attributes">properties</a>. When any of a property's <i>dependencies</i> change, the property is automatically updated too, according to the specified relationship.</li>
<li>The body of <a href="qtqml-syntax-objectattributes.html#signal-attributes">Signal handlers</a>. These JavaScript statements are automatically evaluated whenever a QML object emits the associated signal.</li>
<li>The definition of <a href="qtqml-syntax-objectattributes.html#method-attributes">custom methods</a>. JavaScript functions that are defined within the body of a QML object become methods of that object.</li>
<li>Standalone <a href="qtqml-javascript-imports.html">JavaScript resource (.js) files</a>. These files are actually separate from QML documents, but they can be imported into QML documents. Functions and variables that are defined within the imported files can be used in property bindings, signal handlers, and custom methods.</li>
</ol>
<a name="javascript-in-property-bindings"></a>
<h2 id="javascript-in-property-bindings">JavaScript in Property Bindings</h2>
<p>In the following example, the Rectangle's <code>color</code> depends on the MouseArea's <code>pressed</code> property. This relationship is described using a conditional expression:</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type">Rectangle</span> {
      <span class="name">id</span>: <span class="name">colorbutton</span>
      <span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">80</span>;

      <span class="name">color</span>: <span class="name">mousearea</span>.<span class="name">pressed</span> ? <span class="string">&quot;steelblue&quot;</span> : <span class="string">&quot;lightsteelblue&quot;</span>

      <span class="type">MouseArea</span> {
          <span class="name">id</span>: <span class="name">mousearea</span>
          <span class="name">anchors</span>.fill: <span class="name">parent</span>
      }
  }

</pre>
<p>In fact, any JavaScript expression (no matter how complex) may be used in a property binding definition, as long as the result of the expression is a value whose type can be assigned to the property. This includes side effects. However, complex bindings and side effects are discouraged because they can reduce the performance, readability, and maintainability of the code.</p>
<p>There are two ways to define a property binding: the first (and most common) is, as previously shown, in a <a href="qtqml-syntax-objectattributes.html#value-assignment-on-initialization">property initialization</a>. The second (and much rarer) way is to assign the property a function returned from the <a href="qml-qtqml-qt.html#binding-method">Qt.binding()</a> function, from within imperative JavaScript code, as shown below:</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type">Rectangle</span> {
      <span class="name">id</span>: <span class="name">colorbutton</span>
      <span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">80</span>;

      <span class="name">color</span>: <span class="string">&quot;red&quot;</span>

      <span class="type">MouseArea</span> {
          <span class="name">id</span>: <span class="name">mousearea</span>
          <span class="name">anchors</span>.fill: <span class="name">parent</span>
      }

      <span class="name">Component</span>.onCompleted: {
          <span class="name">color</span> <span class="operator">=</span> <span class="name">Qt</span>.<span class="name">binding</span>(<span class="keyword">function</span>() { <span class="keyword">return</span> <span class="name">mousearea</span>.<span class="name">pressed</span> ? <span class="string">&quot;steelblue&quot;</span> : <span class="string">&quot;lightsteelblue&quot;</span> });
      }
  }

</pre>
<p>See the <a href="qtqml-syntax-propertybinding.html">property bindings</a> documentation for more information about how to define property bindings, and see the documentation about <a href="qtqml-syntax-propertybinding.html#qml-javascript-assignment">Property Assignment versus Property Binding</a> for information about how bindings differ from value assignments.</p>
<a name="javascript-in-signal-handlers"></a>
<h2 id="javascript-in-signal-handlers">JavaScript in Signal Handlers</h2>
<p>QML object types can emit signals in reaction to certain events occurring. Those signals can be handled by signal handler functions, which can be defined by clients to implement custom program logic.</p>
<p>Suppose that a button represented by a Rectangle type has a MouseArea and a Text label. The MouseArea will emit its pressed signal when the user presses the defined interactive area, which will automatically trigger the <code>onPressed</code> handler, which can be defined by clients. The QML engine will execute the JavaScript expressions defined in the <code>onPressed</code> and <code>onReleased</code> handlers, as required. Typically, a signal handler is bound to JavaScript expressions to initiate other events or to simply assign property values.</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type">Rectangle</span> {
      <span class="name">id</span>: <span class="name">button</span>
      <span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">80</span>; <span class="name">color</span>: <span class="string">&quot;lightsteelblue&quot;</span>

      <span class="type">MouseArea</span> {
          <span class="name">id</span>: <span class="name">mousearea</span>
          <span class="name">anchors</span>.fill: <span class="name">parent</span>

          <span class="name">onPressed</span>: {
              <span class="comment">// arbitrary JavaScript expression</span>
              <span class="name">label</span>.<span class="name">text</span> <span class="operator">=</span> <span class="string">&quot;I am Pressed!&quot;</span>
          }
          <span class="name">onReleased</span>: {
              <span class="comment">// arbitrary JavaScript expression</span>
              <span class="name">label</span>.<span class="name">text</span> <span class="operator">=</span> <span class="string">&quot;Click Me!&quot;</span>
          }

      }

      <span class="type">Text</span> {
          <span class="name">id</span>: <span class="name">label</span>
          <span class="name">anchors</span>.centerIn: <span class="name">parent</span>
          <span class="name">text</span>: <span class="string">&quot;Press Me!&quot;</span>
      }
  }

</pre>
<p>Please see the <a href="qtqml-syntax-signals.html">Signal and Handler Event System</a> documentation for in-depth discussion of signals and signal handlers, and see the <a href="qtqml-syntax-objectattributes.html">QML Object Attributes</a> documentation for in-depth discussion of how to define the implementation of signal handlers in QML with JavaScript.</p>
<a name="javascript-in-standalone-functions"></a>
<h2 id="javascript-in-standalone-functions">JavaScript in Standalone Functions</h2>
<p>Program logic can also be defined in JavaScript functions. These functions can be defined inline in QML documents (as custom methods) or externally in imported JavaScript files.</p>
<a name="javascript-in-custom-object-methods"></a>
<h3 >JavaScript in Custom Object Methods</h3>
<p>Custom methods can be defined in QML documents and may be called from signal handlers, property bindings, or functions in other QML objects. Methods defined in this way are often referred to as <i>inline JavaScript functions</i> because their implementation is included in the QML object type definition (QML document), as opposed to an external JavaScript file.</p>
<p>An example of an inline custom method is as follows:</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type">Item</span> {
      <span class="keyword">function</span> <span class="name">factorial</span>(<span class="name">a</span>) {
          <span class="name">a</span> <span class="operator">=</span> <span class="name">parseInt</span>(<span class="name">a</span>);
          <span class="keyword">if</span> (<span class="name">a</span> <span class="operator">&lt;=</span> <span class="number">0</span>)
              <span class="keyword">return</span> <span class="number">1</span>;
          <span class="keyword">else</span>
              <span class="keyword">return</span> <span class="name">a</span> <span class="operator">*</span> <span class="name">factorial</span>(<span class="name">a</span> <span class="operator">-</span> <span class="number">1</span>);
      }

      <span class="type">MouseArea</span> {
          <span class="name">anchors</span>.fill: <span class="name">parent</span>
          <span class="name">onClicked</span>: <span class="name">console</span>.<span class="name">log</span>(<span class="name">factorial</span>(<span class="number">10</span>))
      }
  }

</pre>
<p>The factorial function will run whenever the MouseArea detects a <code>clicked</code> signal.</p>
<p>Importantly, custom methods defined inline in a QML document are exposed to other objects, and therefore inline functions on the root object in a QML component can be invoked by callers outside the component. If this is not desired, the method can be added to a non-root object or, preferably, written in an external JavaScript file.</p>
<p>See the <a href="qtqml-syntax-objectattributes.html">QML Object Attributes</a> documentation for in-depth discussion of how to define custom methods in QML with JavaScript code implementations.</p>
<a name="functions-in-imported-javascript-files"></a>
<h3 >Functions in Imported JavaScript Files</h3>
<p>Non-trivial program logic is best separated into external JavaScript files. These files can be imported into QML files using an <code>import</code> statement, in the same way that <a href="qtqml-modules-topic.html">modules</a> are imported.</p>
<p>For example, the <code>factorial()</code> method in the above example could be moved into an external file named <code>factorial.js</code>, and accessed like this:</p>
<pre class="qml">

  import &quot;factorial.js&quot; as MathFunctions

  <span class="type">Item</span> {
      <span class="type">MouseArea</span> {
          <span class="name">anchors</span>.fill: <span class="name">parent</span>
          <span class="name">onClicked</span>: <span class="name">console</span>.<span class="name">log</span>(<span class="name">MathFunctions</span>.<span class="name">factorial</span>(<span class="number">10</span>))
      }
  }

</pre>
<p>For more information about loading external JavaScript files into QML, read the section about <a href="qtqml-javascript-imports.html">Importing JavaScript Resources in QML</a>.</p>
<a name="connecting-signals-to-javascript-functions"></a>
<h3 >Connecting Signals to JavaScript Functions</h3>
<p>QML object types which emit signals also provide default signal handlers for their signals, as described in a previous section. Sometimes, however, a client will want to cause a signal emitted from one object to trigger a function defined in another object; and in that case, a signal connection is often preferable.</p>
<p>A signal emitted by a QML object may be connected to a JavaScript function by calling the signal's <code>connect()</code> method and passing the JavaScript function as an argument. For example, the following code connects the MouseArea <code>clicked</code> signal to the <code>jsFunction()</code> in <code>script.js</code>:</p>
<div class="table"><table class="generic">
 <tr valign="top" class="odd"><td ><pre class="qml">

  import QtQuick 2.0
  import &quot;script.js&quot; as MyScript

  <span class="type">Item</span> {
      <span class="name">id</span>: <span class="name">item</span>
      <span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">200</span>

      <span class="type">MouseArea</span> {
          <span class="name">id</span>: <span class="name">mouseArea</span>
          <span class="name">anchors</span>.fill: <span class="name">parent</span>
      }

      <span class="name">Component</span>.onCompleted: {
          <span class="name">mouseArea</span>.<span class="name">clicked</span>.<span class="name">connect</span>(<span class="name">MyScript</span>.<span class="name">jsFunction</span>)
      }
  }

</pre>
</td><td ><pre class="js">

  <span class="comment">// script.js</span>

  <span class="keyword">function</span> <span class="name">jsFunction</span>() {
      <span class="name">console</span>.<span class="name">log</span>(<span class="string">&quot;Called JavaScript function!&quot;</span>)
  }

</pre>
</td></tr>
</table></div>
<p>The <code>jsFunction()</code> will now be called whenever MouseArea's <code>clicked</code> signal is emitted.</p>
<p>See <a href="qtqml-syntax-signals.html">Connecting Signals to Methods and Signals</a> for more information.</p>
<a name="javascript-in-application-startup-code"></a>
<h2 id="javascript-in-application-startup-code">JavaScript in Application Startup Code</h2>
<p>It is occasionally necessary to run some imperative code at application (or component instance) startup. While it is tempting to just include the startup script as <i>global code</i> in an external script file, this can have severe limitations as the QML environment may not have been fully established. For example, some objects might not have been created or some <a href="qtqml-syntax-propertybinding.html">property bindings</a> may not have been established. See <a href="qtqml-javascript-hostenvironment.html#javascript-environment-restrictions">JavaScript Environment Restrictions</a> for the exact limitations of global script code.</p>
<p>A QML object will emit the <code>Component.completed</code> <a href="qtqml-syntax-signals.html#attached-signal-handlers">attached signal</a> when its instantiation is complete. JavaScript code in the corresponding <code>Component.onCompleted</code> handler runs after the object is instantiated. Thus, the best place to write application startup code is in the <code>Component.onCompleted</code> handler of the top-level object, because this object emits <code>Component.completed</code> when the QML environment is fully established.</p>
<p>For example:</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type">Rectangle</span> {
      <span class="keyword">function</span> <span class="name">startupFunction</span>() {
          <span class="comment">// ... startup code</span>
      }

      <span class="name">Component</span>.onCompleted: <span class="name">startupFunction</span>();
  }

</pre>
<p>Any object in a QML file - including nested objects and nested QML component instances - can use this attached property. If there is more than one <code>onCompleted()</code> handler to execute at startup, they are run sequentially in an undefined order.</p>
<p>Likewise, every <code>Component</code> will emit a <a href="qml-qtqml-component.html#destruction-signal">destruction()</a> signal just before being destroyed.</p>
</div>
<!-- @@@qtqml-javascript-expressions.html -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2017 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>