140baa798d8cb4ddd0796bbda8515d8c15ffb6c9
[profile/ivi/qtdeclarative.git] / doc / src / qtquick1 / dynamicobjects.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
6 **
7 ** This file is part of the documentation of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:FDL$
10 ** GNU Free Documentation License
11 ** Alternatively, this file may be used under the terms of the GNU Free
12 ** Documentation License version 1.3 as published by the Free Software
13 ** Foundation and appearing in the file included in the packaging of
14 ** this file.
15 **
16 ** Other Usage
17 ** Alternatively, this file may be used in accordance with the terms
18 ** and conditions contained in a signed written agreement between you
19 ** and Nokia.
20 **
21 **
22 **
23 **
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29 \page qdeclarativedynamicobjects.html
30 \inqmlmodule QtQuick 1
31 \ingroup qml-features
32 \contentspage {QML Features}
33 \previouspage {Integrating QML Code with Existing Qt UI Code}
34 \nextpage {Network Transparency}{Loading Resources in QML}
35 \title Dynamic Object Management in QML
36
37 QML provides a number of ways to dynamically create and manage QML objects.
38 The \l{Loader}, \l{Repeater}, \l{ListView}, \l{GridView} and \l{PathView} elements
39 all support dynamic object management.  Objects can also be created and managed
40 from C++, and this is the preferred method for hybrid QML/C++ applications
41 (see \l{Using QML Bindings in C++ Applications}).
42
43 QML also supports the dynamic creation of objects from within JavaScript
44 code. This is useful if the existing QML elements do not fit the needs of your
45 application, and there are no C++ components involved.
46
47 See the \l {declarative/toys/dynamicscene}{Dynamic Scene example} for a demonstration
48 of the concepts discussed on this page.
49
50
51 \section1 Creating Objects Dynamically
52
53 There are two ways to create objects dynamically from JavaScript. You can either call
54 \l {QML:Qt::createComponent()}{Qt.createComponent()} to dynamically create
55 a \l Component object, or use \l{QML:Qt::createQmlObject()}{Qt.createQmlObject()}
56 to create an item from a string of QML.
57 Creating a component is better if you have an existing component defined in a \c .qml
58 file, and you want to dynamically create instances of that component. Otherwise,
59 creating an item from a string of QML is useful when the item QML itself is generated
60 at runtime.
61
62
63 \section2 Creating a Component Dynamically
64
65 To dynamically load a component defined in a QML file, call the
66 \l {QML:Qt::createComponent()}{Qt.createComponent()} function on the \l{QML Global Object}.
67 This function takes the URL of the QML file as its only argument and creates
68 a \l Component object from this URL.
69
70 Once you have a \l Component, you can call its \l {Component::createObject()}{createObject()} method to create an instance of
71 the component. This function can take one or two arguments:
72 \list
73 \o The first is the parent for the new item. Since graphical items will not appear on the scene without a parent, it is 
74   recommended that you set the parent this way. However, if you wish to set the parent later you can safely pass \c null to 
75   this function. 
76 \o The second is optional and is a map of property-value items that define initial any property values for the item.
77   Property values specified by this argument are applied to the object before its creation is finalized, avoiding
78   binding errors that may occur if particular properties must be initialized to enable other property bindings.
79   when certain properties have been bound to before they have been set by the code. Additionally, there are small
80   performance benefits when compared to defining property values and bindings after the object is created.
81 \endlist
82
83 Here is an example. First there is \c Sprite.qml, which defines a simple QML component:
84
85 \snippet doc/src/snippets/declarative/Sprite.qml 0
86
87 Our main application file, \c main.qml, imports a \c componentCreation.js JavaScript file
88 that will create \c Sprite objects:
89
90 \snippet doc/src/snippets/declarative/createComponent.qml 0
91
92 Here is \c componentCreation.js. Notice it checks whether the component \l{Component::status}{status} is
93 \c Component.Ready before calling \l {Component::createObject()}{createObject()}
94 in case the QML file is loaded over a network and thus is not ready immediately.
95
96 \snippet doc/src/snippets/declarative/componentCreation.js vars
97 \codeline
98 \snippet doc/src/snippets/declarative/componentCreation.js func
99 \snippet doc/src/snippets/declarative/componentCreation.js remote
100 \snippet doc/src/snippets/declarative/componentCreation.js func-end
101 \codeline
102 \snippet doc/src/snippets/declarative/componentCreation.js finishCreation
103
104 If you are certain the QML file to be loaded is a local file, you could omit the \c finishCreation()
105 function and call \l {Component::createObject()}{createObject()} immediately:
106
107 \snippet doc/src/snippets/declarative/componentCreation.js func
108 \snippet doc/src/snippets/declarative/componentCreation.js local
109 \snippet doc/src/snippets/declarative/componentCreation.js func-end
110
111 Notice in both instances, \l {Component::createObject()}{createObject()} is called with
112 \c appWindow passed as an argument so that the created object will become a child of the
113 \c appWindow item in \c main.qml. Otherwise, the new item will not appear in the scene.
114
115 When using files with relative paths, the path should
116 be relative to the file where \l {QML:Qt::createComponent()}{Qt.createComponent()} is executed.
117
118 To connect signals to (or receive signals from) dynamically created objects,
119 use the signal \c connect() method. See
120 \l{QML Signal and Handler Event System#Connecting Signals to Methods and Signals}
121 {Connecting Signals to Methods and Signals} for more information.
122
123
124 \section2 Creating an Object from a String of QML
125
126 If the QML is not defined until runtime, you can create a QML item from
127 a string of QML using the \l{QML:Qt::createQmlObject()}{Qt.createQmlObject()} function, as in the following example:
128
129 \snippet doc/src/snippets/declarative/createQmlObject.qml 0
130
131 The first argument is the string of QML to create. Just like in a new file, you will need to
132 import any types you wish to use. The second argument is the parent item for the new item;
133 this should be an existing item in the scene. The third argument is the file path to associate
134 with the new item; this is used for error reporting.
135
136 If the string of QML imports files using relative paths, the path should be relative
137 to the file in which the parent item (the second argument to the method) is defined.
138
139
140 \section1 Maintaining Dynamically Created Objects
141
142 When managing dynamically created items, you must ensure the creation context
143 outlives the created item. Otherwise, if the creation context is destroyed first,
144 the bindings in the dynamic item will no longer work.
145
146 The actual creation context depends on how an item is created:
147
148 \list
149 \o If \l {QML:Qt::createComponent()}{Qt.createComponent()} is used, the creation context
150    is the QDeclarativeContext in which this method is called
151 \o If \l{QML:Qt::createQmlObject()}{Qt.createQmlObject()}
152    if called, the creation context is the context of the parent item passed to this method
153 \o If a \c {Component{}} item is defined and \l {Component::createObject()}{createObject()}
154    is called on that item, the creation context is the context in which the \c Component is defined
155 \endlist
156
157 Also, note that while dynamically created objects may be used the same as other objects, they
158 do not have an id in QML.
159
160
161 \section1 Deleting Objects Dynamically
162
163 In many user interfaces, it is sufficient to set an item's opacity to 0 or
164 to move the item off the screen instead of deleting the item. If you have
165 lots of dynamically created items, however, you may receive a worthwhile
166 performance benefit if unused items are deleted.
167
168 Note that you should never manually delete items that were dynamically created
169 by QML elements (such as \l Loader and \l Repeater). Also, you should avoid deleting
170 items that you did not dynamically create yourself.
171
172 Items can be deleted using the \c destroy() method. This method has an optional
173 argument (which defaults to 0) that specifies the approximate delay in milliseconds
174 before the object is to be destroyed.
175
176 Here is an example. The \c application.qml creates five instances of the \c SelfDestroyingRect.qml
177 component. Each instance runs a NumberAnimation, and when the animation has finished, calls
178 \c destroy() on its root item to destroy itself:
179
180 \table
181 \row
182 \o \c application.qml
183 \o \c SelfDestroyingRect.qml
184
185 \row
186 \o \snippet doc/src/snippets/declarative/dynamicObjects-destroy.qml 0
187 \o \snippet doc/src/snippets/declarative/SelfDestroyingRect.qml 0
188
189 \endtable
190
191 Alternatively, the \c application.qml could have destroyed the created object
192 by calling \c object.destroy().
193
194 Note that it is safe to call destroy() on an object within that object. Objects are not destroyed the
195 instant destroy() is called, but are cleaned up sometime between the end of that script block and the next frame
196 (unless you specified a non-zero delay).
197
198 Note also that if a \c SelfDestroyingRect instance was created statically like this:
199
200 \qml
201 Item {
202     SelfDestroyingRect {
203         // ...
204     }
205 }
206 \endqml
207
208 This would result in an error, since items can only be dynamically
209 destroyed if they were dynamically created.
210
211 Objects created with \l{QML:Qt::createQmlObject()}{Qt.createQmlObject()}
212 can similarly be destroyed using \c destroy():
213
214 \snippet doc/src/snippets/declarative/createQmlObject.qml 0
215 \snippet doc/src/snippets/declarative/createQmlObject.qml destroy
216 */