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