Sophie

Sophie

distrib > Fedora > 18 > x86_64 > by-pkgid > ff187cb994c94c614ecc64c5a8528b1b > files > 5076

qt-doc-4.8.5-10.fc18.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- dynamicobjects.qdoc -->
  <title>Qt 4.8: Dynamic Object Management in QML</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script src="scripts/jquery.js" type="text/javascript"></script>
  <script src="scripts/functions.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />
  <!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->

<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>

</head>
<body class="" onload="CheckEmptyAndLoadList();">
 <div class="header" id="qtdocheader">
    <div class="content"> 
    <div id="nav-logo">
      <a href="index.html">Home</a></div>
    <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
    <div id="narrowsearch"></div>
    <div id="nav-topright">
      <ul>
        <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
        <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
        <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
          DOC</a></li>
        <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
      </ul>
    </div>
    <div id="shortCut">
      <ul>
        <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
        <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS        </a></li>
      </ul>
     </div>
 <ul class="sf-menu" id="narrowmenu"> 
             <li><a href="#">API Lookup</a> 
                 <ul> 
                     <li><a href="classes.html">Class index</a></li> 
           <li><a href="functions.html">Function index</a></li> 
           <li><a href="modules.html">Modules</a></li> 
           <li><a href="namespaces.html">Namespaces</a></li> 
           <li><a href="qtglobal.html">Global Declarations</a></li> 
           <li><a href="qdeclarativeelements.html">QML elements</a></li> 
             </ul> 
             </li> 
             <li><a href="#">Qt Topics</a> 
                 <ul> 
                        <li><a href="qt-basic-concepts.html">Programming with Qt</a></li>  
                        <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li>  
                        <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>  
                        <li><a href="supported-platforms.html">Supported Platforms</a></li>  
                        <li><a href="technology-apis.html">Qt and Key Technologies</a></li>  
                        <li><a href="best-practices.html">How-To's and Best Practices</a></li>  
              </ul> 
                 </li> 
                 <li><a href="#">Examples</a> 
                     <ul> 
                       <li><a href="all-examples.html">Examples</a></li> 
                       <li><a href="tutorials.html">Tutorials</a></li> 
                       <li><a href="demos.html">Demos</a></li> 
                       <li><a href="qdeclarativeexamples.html">QML Examples</a></li> 
                </ul> 
                     </li> 
                 </ul> 
    </div>
  </div>
  <div class="wrapper">
    <div class="hd">
      <span></span>
    </div>
    <div class="bd group">
      <div class="sidebar">
        <div class="searchlabel">
          Search index:</div>
        <div class="search" id="sidebarsearch">
          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />
 <div id="resultdialog"> 
 <a href="#" id="resultclose">Close</a> 
 <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> 
 <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> 
 <ul id="resultlist" class="all"> 
 </ul> 
 </div> 
            </fieldset>
          </form>
        </div>
        <div class="box first bottombar" id="lookup">
          <h2 title="API Lookup"><span></span>
            API Lookup</h2>
          <div  id="list001" class="list">
          <ul id="ul001" >
              <li class="defaultLink"><a href="classes.html">Class index</a></li>
              <li class="defaultLink"><a href="functions.html">Function index</a></li>
              <li class="defaultLink"><a href="modules.html">Modules</a></li>
              <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
              <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
              <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
            </ul> 
          </div>
        </div>
        <div class="box bottombar" id="topics">
          <h2 title="Qt Topics"><span></span>
            Qt Topics</h2>
          <div id="list002" class="list">
            <ul id="ul002" >
               <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> 
               <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> 
               <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> 
               <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>  
               <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> 
               <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> 
            </ul>  
          </div>
        </div>
        <div class="box" id="examples">
          <h2 title="Examples"><span></span>
            Examples</h2>
          <div id="list003" class="list">
        <ul id="ul003">
              <li class="defaultLink"><a href="all-examples.html">Examples</a></li>
              <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
              <li class="defaultLink"><a href="demos.html">Demos</a></li>
              <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
            </ul> 
          </div>
        </div>
      </div>
      <div class="wrap">
        <div class="toolbar">
          <div class="breadcrumb toolblock">
            <ul>
              <li class="first"><a href="index.html">Home</a></li>
              <!--  Breadcrumbs go here -->
<li>Dynamic Object Management in QML</li>
            </ul>
          </div>
          <div class="toolbuttons toolblock">
            <ul>
              <li id="smallA" class="t_button">A</li>
              <li id="medA" class="t_button active">A</li>
              <li id="bigA" class="t_button">A</li>
              <li id="print" class="t_button"><a href="javascript:this.print();">
                <span>Print</span></a></li>
            </ul>
        </div>
        </div>
        <div class="content mainContent">
  <link rel="prev" href="qml-integration.html" />
  <link rel="next" href="qdeclarativenetwork.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="qml-integration.html">Integrating QML Code with Existing Qt UI Code</a>
<a class="nextPage" href="qdeclarativenetwork.html">Loading Resources in QML</a>
</p><p/>
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#creating-objects-dynamically">Creating Objects Dynamically</a></li>
<li class="level2"><a href="#creating-a-component-dynamically">Creating a Component Dynamically</a></li>
<li class="level2"><a href="#creating-an-object-from-a-string-of-qml">Creating an Object from a String of QML</a></li>
<li class="level1"><a href="#maintaining-dynamically-created-objects">Maintaining Dynamically Created Objects</a></li>
<li class="level1"><a href="#deleting-objects-dynamically">Deleting Objects Dynamically</a></li>
</ul>
</div>
<h1 class="title">Dynamic Object Management in QML</h1>
<span class="subtitle"></span>
<!-- $$$qdeclarativedynamicobjects.html-description -->
<div class="descr"> <a name="details"></a>
<p>QML provides a number of ways to dynamically create and manage QML objects. The <a href="qml-loader.html">Loader</a>, <a href="qml-repeater.html">Repeater</a>, <a href="qml-listview.html">ListView</a>, <a href="qml-gridview.html">GridView</a> and <a href="qml-pathview.html">PathView</a> elements all support dynamic object management. Objects can also be created and managed from C++, and this is the preferred method for hybrid QML/C++ applications (see <a href="qtbinding.html">Using QML Bindings in C++ Applications</a>).</p>
<p>QML also supports the dynamic creation of objects from within JavaScript code. This is useful if the existing QML elements do not fit the needs of your application, and there are no C++ components involved.</p>
<p>See the <a href="declarative-toys-dynamicscene.html">Dynamic Scene example</a> for a demonstration of the concepts discussed on this page.</p>
<a name="creating-objects-dynamically"></a>
<h2>Creating Objects Dynamically</h2>
<p>There are two ways to create objects dynamically from JavaScript. You can either call <a href="qml-qt.html#createComponent-method">Qt.createComponent()</a> to dynamically create a <a href="qml-component.html">Component</a> object, or use <a href="qml-qt.html#createQmlObject-method">Qt.createQmlObject()</a> to create an item from a string of QML. Creating a component is better if you have an existing component defined in a <tt>.qml</tt> file, and you want to dynamically create instances of that component. Otherwise, creating an item from a string of QML is useful when the item QML itself is generated at runtime.</p>
<a name="creating-a-component-dynamically"></a>
<h3>Creating a Component Dynamically</h3>
<p>To dynamically load a component defined in a QML file, call the <a href="qml-qt.html#createComponent-method">Qt.createComponent()</a> function on the <a href="qdeclarativeglobalobject.html">QML Global Object</a>. This function takes the URL of the QML file as its only argument and creates a <a href="qml-component.html">Component</a> object from this URL.</p>
<p>Once you have a <a href="qml-component.html">Component</a>, you can call its <a href="qml-component.html#createObject-method">createObject()</a> method to create an instance of the component. This function can take one or two arguments:</p>
<ul>
<li>The first is the parent for the new item. Since graphical items will not appear on the scene without a parent, it is recommended that you set the parent this way. However, if you wish to set the parent later you can safely pass <tt>null</tt> to this function.</li>
<li>The second is optional and is a map of property-value items that define initial any property values for the item. Property values specified by this argument are applied to the object before its creation is finalized, avoiding binding errors that may occur if particular properties must be initialized to enable other property bindings. when certain properties have been bound to before they have been set by the code. Additionally, there are small performance benefits when compared to defining property values and bindings after the object is created.</li>
</ul>
<p>Here is an example. First there is <tt>Sprite.qml</tt>, which defines a simple QML component:</p>
<pre class="qml"> import QtQuick 1.0

 <span class="type"><a href="qml-rectangle.html">Rectangle</a></span> { <span class="name">width</span>: <span class="number">80</span>; <span class="name">height</span>: <span class="number">50</span>; <span class="name">color</span>: <span class="string">&quot;red&quot;</span> }</pre>
<p>Our main application file, <tt>main.qml</tt>, imports a <tt>componentCreation.js</tt> JavaScript file that will create <tt>Sprite</tt> objects:</p>
<pre class="qml"> import QtQuick 1.0
 import &quot;componentCreation.js&quot; as MyScript

 <span class="type"><a href="qml-rectangle.html">Rectangle</a></span> {
     <span class="name">id</span>: <span class="name">appWindow</span>
     <span class="name">width</span>: <span class="number">300</span>; <span class="name">height</span>: <span class="number">300</span>

     <span class="name">Component</span>.onCompleted: <span class="name">MyScript</span>.<span class="name">createSpriteObjects</span>();
 }</pre>
<p>Here is <tt>componentCreation.js</tt>. Notice it checks whether the component <a href="qml-component.html#status-prop">status</a> is <tt>Component.Ready</tt> before calling <a href="qml-component.html#createObject-method">createObject()</a> in case the QML file is loaded over a network and thus is not ready immediately.</p>
<pre class="js"> var <span class="name">component</span>;
 var <span class="name">sprite</span>;

 <span class="keyword">function</span> <span class="name">createSpriteObjects</span>() {
     <span class="name">component</span> <span class="operator">=</span> <span class="name">Qt</span>.<span class="name">createComponent</span>(<span class="string">&quot;Sprite.qml&quot;</span>);
     <span class="keyword">if</span> (<span class="name">component</span>.<span class="name">status</span> <span class="operator">==</span> <span class="name">Component</span>.<span class="name">Ready</span>)
         <span class="name">finishCreation</span>();
     else
         <span class="name">component</span>.<span class="name">statusChanged</span>.<span class="name">connect</span>(<span class="name">finishCreation</span>);
 }

 <span class="keyword">function</span> <span class="name">finishCreation</span>() {
     <span class="keyword">if</span> (<span class="name">component</span>.<span class="name">status</span> <span class="operator">==</span> <span class="name">Component</span>.<span class="name">Ready</span>) {
         <span class="name">sprite</span> <span class="operator">=</span> <span class="name">component</span>.<span class="name">createObject</span>(<span class="name">appWindow</span>, {&quot;x&quot;: <span class="number">100</span>, &quot;y&quot;: 100});
         <span class="keyword">if</span> (<span class="name">sprite</span> <span class="operator">==</span> <span class="number">null</span>) {
             <span class="comment">// Error Handling</span>
             <span class="name">console</span>.<span class="name">log</span>(<span class="string">&quot;Error creating object&quot;</span>);
         }
     } else <span class="keyword">if</span> (<span class="name">component</span>.<span class="name">status</span> <span class="operator">==</span> <span class="name">Component</span>.<span class="name">Error</span>) {
         <span class="comment">// Error Handling</span>
         <span class="name">console</span>.<span class="name">log</span>(<span class="string">&quot;Error loading component:&quot;</span>, <span class="name">component</span>.<span class="name">errorString</span>());
     }
 }</pre>
<p>If you are certain the QML file to be loaded is a local file, you could omit the <tt>finishCreation()</tt> function and call <a href="qml-component.html#createObject-method">createObject()</a> immediately:</p>
<pre class="js"> <span class="keyword">function</span> <span class="name">createSpriteObjects</span>() {
     <span class="name">component</span> <span class="operator">=</span> <span class="name">Qt</span>.<span class="name">createComponent</span>(<span class="string">&quot;Sprite.qml&quot;</span>);
     <span class="name">sprite</span> <span class="operator">=</span> <span class="name">component</span>.<span class="name">createObject</span>(<span class="name">appWindow</span>, {&quot;x&quot;: <span class="number">100</span>, &quot;y&quot;: 100});

     <span class="keyword">if</span> (<span class="name">sprite</span> <span class="operator">==</span> <span class="number">null</span>) {
         <span class="comment">// Error Handling</span>
         <span class="name">console</span>.<span class="name">log</span>(<span class="string">&quot;Error creating object&quot;</span>);
     }
 }</pre>
<p>Notice in both instances, <a href="qml-component.html#createObject-method">createObject()</a> is called with <tt>appWindow</tt> passed as an argument so that the created object will become a child of the <tt>appWindow</tt> item in <tt>main.qml</tt>. Otherwise, the new item will not appear in the scene.</p>
<p>When using files with relative paths, the path should be relative to the file where <a href="qml-qt.html#createComponent-method">Qt.createComponent()</a> is executed.</p>
<p>To connect signals to (or receive signals from) dynamically created objects, use the signal <tt>connect()</tt> method. See <a href="qmlevents.html#connecting-signals-to-methods-and-signals">Connecting Signals to Methods and Signals</a> for more information.</p>
<a name="creating-an-object-from-a-string-of-qml"></a>
<h3>Creating an Object from a String of QML</h3>
<p>If the QML is not defined until runtime, you can create a QML item from a string of QML using the <a href="qml-qt.html#createQmlObject-method">Qt.createQmlObject()</a> function, as in the following example:</p>
<pre class="qml"> var <span class="name">newObject</span> = <span class="name">Qt</span>.<span class="name">createQmlObject</span>(<span class="string">'import QtQuick 1.0; Rectangle {color: &quot;red&quot;; width: 20; height: 20}'</span>,
     <span class="name">parentItem</span>, <span class="string">&quot;dynamicSnippet1&quot;</span>);</pre>
<p>The first argument is the string of QML to create. Just like in a new file, you will need to import any types you wish to use. The second argument is the parent item for the new item; this should be an existing item in the scene. The third argument is the file path to associate with the new item; this is used for error reporting.</p>
<p>If the string of QML imports files using relative paths, the path should be relative to the file in which the parent item (the second argument to the method) is defined.</p>
<a name="maintaining-dynamically-created-objects"></a>
<h2>Maintaining Dynamically Created Objects</h2>
<p>When managing dynamically created items, you must ensure the creation context outlives the created item. Otherwise, if the creation context is destroyed first, the bindings in the dynamic item will no longer work.</p>
<p>The actual creation context depends on how an item is created:</p>
<ul>
<li>If <a href="qml-qt.html#createComponent-method">Qt.createComponent()</a> is used, the creation context is the <a href="qdeclarativecontext.html">QDeclarativeContext</a> in which this method is called</li>
<li>If <a href="qml-qt.html#createQmlObject-method">Qt.createQmlObject()</a> if called, the creation context is the context of the parent item passed to this method</li>
<li>If a <tt>Component{}</tt> item is defined and <a href="qml-component.html#createObject-method">createObject()</a> is called on that item, the creation context is the context in which the <tt>Component</tt> is defined</li>
</ul>
<p>Also, note that while dynamically created objects may be used the same as other objects, they do not have an id in QML.</p>
<a name="deleting-objects-dynamically"></a>
<h2>Deleting Objects Dynamically</h2>
<p>In many user interfaces, it is sufficient to set an item's opacity to 0 or to move the item off the screen instead of deleting the item. If you have lots of dynamically created items, however, you may receive a worthwhile performance benefit if unused items are deleted.</p>
<p>Note that you should never manually delete items that were dynamically created by QML elements (such as <a href="qml-loader.html">Loader</a> and <a href="qml-repeater.html">Repeater</a>). Also, you should avoid deleting items that you did not dynamically create yourself.</p>
<p>Items can be deleted using the <tt>destroy()</tt> method. This method has an optional argument (which defaults to 0) that specifies the approximate delay in milliseconds before the object is to be destroyed.</p>
<p>Here is an example. The <tt>application.qml</tt> creates five instances of the <tt>SelfDestroyingRect.qml</tt> component. Each instance runs a <a href="qml-numberanimation.html">NumberAnimation</a>, and when the animation has finished, calls <tt>destroy()</tt> on its root item to destroy itself:</p>
<table class="generic">
<tr valign="top" class="odd"><td ><tt>application.qml</tt></td><td ><tt>SelfDestroyingRect.qml</tt></td></tr>
<tr valign="top" class="even"><td ><pre class="qml"> import QtQuick 1.0

 <span class="type"><a href="qml-item.html">Item</a></span> {
     <span class="name">id</span>: <span class="name">container</span>
     <span class="name">width</span>: <span class="number">500</span>; <span class="name">height</span>: <span class="number">100</span>

     <span class="name">Component</span>.onCompleted: {
         var <span class="name">component</span> = <span class="name">Qt</span>.<span class="name">createComponent</span>(<span class="string">&quot;SelfDestroyingRect.qml&quot;</span>);
         <span class="keyword">for</span> (<span class="keyword">var</span> <span class="name">i</span>=<span class="number">0</span>; <span class="name">i</span><span class="operator">&lt;</span><span class="number">5</span>; i++) {
             var <span class="name">object</span> = <span class="name">component</span>.<span class="name">createObject</span>(<span class="name">container</span>);
             <span class="name">object</span>.<span class="name">x</span> <span class="operator">=</span> (<span class="name">object</span>.<span class="name">width</span> <span class="operator">+</span> <span class="number">10</span>) <span class="operator">*</span> <span class="name">i</span>;
         }
     }
 }</pre>
</td><td ><pre class="qml"> import QtQuick 1.0

 <span class="type"><a href="qml-rectangle.html">Rectangle</a></span> {
     <span class="name">id</span>: <span class="name">rect</span>
     <span class="name">width</span>: <span class="number">80</span>; <span class="name">height</span>: <span class="number">80</span>
     <span class="name">color</span>: <span class="string">&quot;red&quot;</span>

     NumberAnimation on <span class="name">opacity</span> {
         <span class="name">to</span>: <span class="number">0</span>
         <span class="name">duration</span>: <span class="number">1000</span>

         <span class="name">onRunningChanged</span>: {
             <span class="keyword">if</span> (!<span class="name">running</span>) {
                 <span class="name">console</span>.<span class="name">log</span>(<span class="string">&quot;Destroying...&quot;</span>)
                 <span class="name">rect</span>.<span class="name">destroy</span>();
             }
         }
     }
 }</pre>
</td></tr>
</table>
<p>Alternatively, the <tt>application.qml</tt> could have destroyed the created object by calling <tt>object.destroy()</tt>.</p>
<p>Note that it is safe to call destroy() on an object within that object. Objects are not destroyed the instant destroy() is called, but are cleaned up sometime between the end of that script block and the next frame (unless you specified a non-zero delay).</p>
<p>Note also that if a <tt>SelfDestroyingRect</tt> instance was created statically like this:</p>
<pre class="qml"> <span class="type"><a href="qml-item.html">Item</a></span> {
     <span class="type">SelfDestroyingRect</span> {
         <span class="comment">// ...</span>
     }
 }</pre>
<p>This would result in an error, since items can only be dynamically destroyed if they were dynamically created.</p>
<p>Objects created with <a href="qml-qt.html#createQmlObject-method">Qt.createQmlObject()</a> can similarly be destroyed using <tt>destroy()</tt>:</p>
<pre class="qml"> var <span class="name">newObject</span> = <span class="name">Qt</span>.<span class="name">createQmlObject</span>(<span class="string">'import QtQuick 1.0; Rectangle {color: &quot;red&quot;; width: 20; height: 20}'</span>,
     <span class="name">parentItem</span>, <span class="string">&quot;dynamicSnippet1&quot;</span>);
 <span class="name">newObject</span>.<span class="name">destroy</span>(<span class="number">1000</span>);</pre>
</div>
<!-- @@@qdeclarativedynamicobjects.html -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="qml-integration.html">Integrating QML Code with Existing Qt UI Code</a>
<a class="nextPage" href="qdeclarativenetwork.html">Loading Resources in QML</a>
</p>
      </div>
    </div>
    </div> 
    <div class="ft">
      <span></span>
    </div>
  </div> 
  <div class="footer">
    <p>
      <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.</p>
    <br />
    <p>
      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.</p>
    <p>
      Documentation sources may be obtained from <a href="http://www.qt-project.org">
      www.qt-project.org</a>.</p>
    <br />
    <p>
      Digia, Qt and their respective logos are trademarks of Digia Plc 
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. <a title="Privacy Policy"
      href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
  </div>

  <script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>