Change copyrights from Nokia to Digia
[profile/ivi/qtdeclarative.git] / src / qml / doc / src / cppintegration / data.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Free Documentation License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Free
19 ** Documentation License version 1.3 as published by the Free Software
20 ** Foundation and appearing in the file included in the packaging of
21 ** this file.  Please review the following information to ensure
22 ** the GNU Free Documentation License version 1.3 requirements
23 ** will be met: http://www.gnu.org/copyleft/fdl.html.
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27 /*!
28 \page qtqml-cppintegration-data.html
29 \title Data Type Conversion Between QML and C++
30 \brief Description of how data types are exchanged between QML and C++
31
32 When data values are exchanged between QML and C++, they are converted by the
33 QML engine to have the correct data types as appropriate for use in QML or
34 C++. This requires the exchanged data to be of a type that is recognizable by
35 the engine.
36
37 The QML engine provides built-in support for a large number of Qt C++ data
38 types. Additionally, custom C++ types may be registered with the QML type
39 system to make them available to the engine.
40
41 This page discusses the data types supported by the QML engine and how
42 they are converted between QML and C++.
43
44
45 \section1 Data Ownership
46
47 When data is transferred from C++ to QML, the ownership of the data always
48 remains with C++. The exception to this rule is when a QObject is returned from
49 an explicit C++ method call: in this case, the QML engine assumes ownership of
50 the object, unless the ownership of the object has explicitly been set to
51 remain with C++ by invoking QQmlEngine::setObjectOwnership() with
52 QQmlEngine::CppOwnership specified.
53
54 Additionally, the QML engine respects the normal QObject parent ownership
55 semantics of Qt C++ objects, and will not ever take ownership of a QObject
56 instance which already has a parent.
57
58
59 \section1 Basic Qt Data Types
60
61 By default, QML recognizes the following Qt data types, which are
62 automatically converted to a corresponding \l {QML Basic Type}{QML basic type}
63 when passed from C++ to QML and vice-versa:
64
65 \table
66     \row
67         \li Qt Type
68         \li QML Basic Type
69     \row
70         \li bool
71         \li \l bool
72     \row
73         \li unsigned int, int
74         \li \l int
75     \row
76         \li double
77         \li \l double
78     \row
79         \li float, qreal
80         \li \l real
81     \row
82         \li QString
83         \li \l string
84     \row
85         \li QUrl
86         \li real
87     \row
88         \li QColor
89         \li \l color
90     \row
91         \li QFont
92         \li \l font
93     \row
94         \li QDate
95         \li \l date
96     \row
97         \li QTime, QDateTime
98         \li \l time
99     \row
100         \li QPoint, QPointF
101         \li \l point
102     \row
103         \li QSize, QSizeF
104         \li \l size
105     \row
106         \li QRect, QRectF
107         \li \l rect
108     \row
109         \li QMatrix4x4
110         \li \l matrix4x4
111     \row
112         \li QQuaternion
113         \li \l quaternion
114     \row
115         \li QVector2D, QVector3D, QVector4D
116         \li \l vector2d, \l vector3d, \l vector4d
117     \row
118         \li Enums declared with Q_ENUMS()
119         \li \l enumeration
120 \endtable
121
122 (Note that classes provided by the QtGui module, such as QColor, QFont,
123 QQuaternion and QMatrix4x4, are only available from QML when the \l QtQuick
124 module is imported.)
125
126 As a convenience, many of these types can be specified in QML by string values,
127 or by a related method provided by the \l {QML:Qt} object. For example, the \l
128 {Image::sourceSize} property is of type \l size (which automatically translates
129 to the QSize type) and can be specified by a string value formatted as
130 "width\c{x}height", or by the Qt.size() function:
131
132 \qml
133 Item {
134     Image { sourceSize: "100x200" }
135     Image { sourceSize: Qt.size(100, 200) }
136 }
137 \endqml
138
139 See documentation for each individual type under \l {QML Basic Types} for more
140 information.
141
142
143 \section1 QObject-derived Types
144
145 Any QObject-derived class may be used as a type for the exchange of data between
146 QML and C++, providing the class has been registered with the QML type system.
147
148 The engine allows the registration of both instantiable and non-instantiable
149 types. Once a class is registered as a QML type, it can be used as a data type
150 for exchanging data between QML and C++. See
151 \l{qtqml-cppintegration-definetypes.html#registering-c++-types-with-the-qml-type-system}{Registering C++ types with the QML type system} for further details on type registration.
152
153
154 \section1 Conversion Between Qt and JavaScript Types
155
156 The QML engine has built-in support for converting a number of Qt types to
157 related JavaScript types, and vice-versa, when transferring data between QML
158 and C++. This makes it possible to use these types and receive them in C++ or
159 JavaScript without needing to implement custom types that provide access to
160 the data values and their attributes.
161
162 (Note that the JavaScript environment in QML modifies native JavaScript object
163 prototypes, including those of \c String, \c Date and \c Number, to provide
164 additional features. See the \l {qtqml-javascript-hostenvironment.html}
165 {JavaScript Host Environment} for further details.)
166
167
168 \section2 QVariantList and QVariantMap to JavaScript Array and Object
169
170 The QML engine provides automatic type conversion between QVariantList and
171 JavaScript arrays, and between QVariantMap and JavaScript objects.
172
173 For example, the function defined in QML below left expects two arguments, an
174 array and an object, and prints their contents using the standard JavaScript
175 syntax for array and object item access. The C++ code below right calls this
176 function, passing a QVariantList and a QVariantMap, which are automatically
177 converted to JavaScript array and object values, repectively:
178
179 \table
180 \header
181 \row
182 \li \snippet qml/qtbinding/variantlistmap/MyItem.qml 0
183 \li \snippet qml/qtbinding/variantlistmap/main.cpp 0
184 \endtable
185
186 This produces output like:
187
188 \code
189 Array item: 10
190 Array item: #00ff00
191 Array item: bottles
192 Object item: language = QML
193 Object item: released = Tue Sep 21 2010 00:00:00 GMT+1000 (EST)
194 \endcode
195
196 Similarly, if a C++ type uses a QVariantList or QVariantMap type for a property
197 type or method parameter, the value can be created as a JavaScript array or
198 object in QML, and is automatically converted to a QVariantList or QVariantMap
199 when it is passed to C++.
200
201
202 \section2 QDateTime to JavaScript Date
203
204 The QML engine provides automatic type conversion between QDateTime values and
205 JavaScript \c Date objects.
206
207 For example, the function defined in QML below left expects a JavaScript
208 \c Date object, and also returns a new \c Date object with the current date and
209 time. The C++ code below right calls this function, passing a QDateTime value
210 that is automatically converted by the engine into a \c Date object when it is
211 passed to the \c readDate() function. In turn, the readDate() function returns
212 a \c Date object that is automatically converted into a QDateTime value when it
213 is received in C++:
214
215 \table
216 \header
217 \row
218
219 \li
220 \qml
221 // MyItem.qml
222 Item {
223     function readDate(dt) {
224         console.log("The given date is:", dt.toUTCString());
225         return new Date();
226     }
227 }
228 \endqml
229
230 \li
231 \code
232 // C++
233 QQuickView view(QUrl::fromLocalFile("MyItem.qml"));
234
235 QDateTime dateTime = QDateTime::currentDateTime();
236 QDateTime retValue;
237
238 QMetaObject::invokeMethod(view.rootObject(), "readDate",
239         Q_RETURN_ARG(QVariant, retValue),
240         Q_ARG(QVariant, QVariant::fromValue(dateTime)));
241
242 qDebug() << "Value returned from readDate():" << retValue;
243 \endcode
244
245 \endtable
246
247 Similarly, if a C++ type uses a QDateTime for a property type or method
248 parameter, the value can be created as a JavaScript \c Date object in QML, and
249 is automatically converted to a QDateTime value when it is passed to C++.
250
251
252 \section2 Sequence Type to JavaScript Array
253
254 Certain C++ sequence types are supported transparently in QML as JavaScript
255 \c Array types.
256
257 In particular, QML currently supports:
258 \list
259   \li \c {QList<int>}
260   \li \c {QList<qreal>}
261   \li \c {QList<bool>}
262   \li \c {QList<QString>} and \c{QStringList}
263   \li \c {QList<QUrl>}
264 \endlist
265
266 These sequence types are implemented directly in terms of the underlying C++
267 sequence. There are two ways in which such sequences can be exposed to QML:
268 as a Q_PROPERTY of the given sequence type; or as the return type of a
269 Q_INVOKABLE method. There are some differences in the way these are
270 implemented, which are important to note.
271
272 If the sequence is exposed as a Q_PROPERTY, accessing any value in the
273 sequence by index will cause the sequence data to be read from the QObject's
274 property, then a read to occur. Similarly, modifying any value in the
275 sequence will cause the sequence data to be read, and then the modification
276 will be performed and the modified sequence will be written back to the
277 QObject's property.
278
279 If the sequence is returned from a Q_INVOKABLE function, access and mutation
280 is much cheaper, as no QObject property read or write occurs; instead, the
281 C++ sequence data is accessed and modified directly.
282
283 Other sequence types are not supported transparently, and instead an
284 instance of any other sequence type will be passed between QML and C++ as an
285 opaque QVariantList.
286
287 \b {Important Note:} There are some minor differences between the
288 semantics of such sequence Array types and default JavaScript Array types
289 which result from the use of a C++ storage type in the implementation. In
290 particular, deleting an element from an Array will result in a
291 default-constructed value replacing that element, rather than an Undefined
292 value. Similarly, setting the length property of the Array to a value larger
293 than its current value will result in the Array being padded out to the
294 specified length with default-constructed elements rather than Undefined
295 elements.  Finally, the Qt container classes support signed (rather than
296 unsigned) integer indexes; thus, attempting to access any index greater
297 than INT_MAX will fail.
298
299 The default-constructed values for each sequence type are as follows:
300 \table
301 \row \li QList<int> \li integer value 0
302 \row \li QList<qreal> \li real value 0.0
303 \row \li QList<bool> \li boolean value \c {false}
304 \row \li QList<QString> and QStringList \li empty QString
305 \row \li QList<QUrl> \li empty QUrl
306 \endtable
307
308 If you wish to remove elements from a sequence rather than simply replace
309 them with default constructed values, do not use the indexed delete operator
310 ("delete sequence[i]") but instead use the \c {splice} function
311 ("sequence.splice(startIndex, deleteCount)").
312
313
314 \section1 Enumeration Types
315
316 To use a custom enumeration as a data type, its class must be registered and
317 the enumeration must also be declared with Q_ENUMS() to register it with Qt's
318 meta object system. For example, the \c Message class below has a \c Status
319 enum:
320
321 \code
322  class Message : public QObject
323  {
324      Q_OBJECT
325      Q_ENUMS(Status)
326      Q_PROPERTY(Status status READ status NOTIFY statusChanged)
327  public:
328      enum Status {
329          Ready,
330          Loading,
331          Error
332      };
333      Status status() const;
334  signals:
335      void statusChanged();
336  };
337 \endcode
338
339 Providing the \c Message class has been
340 \l{qtqml-cppintegration-definetypes.html#registering-c++-types-with-the-qml-type-system}{registered} with the QML type system, its \c Status enum can be used from QML:
341
342 \qml
343 Message {
344      onStatusChanged: {
345          if (status == Message.Ready)
346              console.log("Message is loaded!")
347      }
348  }
349 \endqml
350
351 \note The names of enum values must begin with a capital letter in order to
352 be accessible from QML.
353
354
355 \section2 Enumeration Types as Signal and Method Parameters
356
357 C++ signals and methods with enumeration-type parameters can be used from QML
358 provided that the enumeration and the signal or method are both declared
359 within the same class, or that the enumeration value is one of those declared
360 in the \l {Qt}{Qt Namespace}.
361
362 Additionally, if a C++ signal with an enum parameter should be connectable to a
363 QML function using the \l{qtqml-syntax-signals.html#connecting-signals-to-methods-and-signals}
364 {connect()} function, the enum type must be registered
365 using qRegisterMetaType().
366
367 For QML signals, enum values may be passed as signal parameters using the \c int
368 type:
369
370 \qml
371  Message {
372      signal someOtherSignal(int statusValue)
373
374      Component.onCompleted: {
375          someOtherSignal(Message.Loading)
376      }
377  }
378 \endqml
379
380 */