1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the documentation of the Qt Toolkit.
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.
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.
26 ****************************************************************************/
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++
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
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.
41 This page discusses the data types supported by the QML engine and how
42 they are converted between QML and C++.
45 \section1 Data Ownership
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.
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.
59 \section1 Basic Qt Data Types
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:
115 \li QVector2D, QVector3D, QVector4D
116 \li \l vector2d, \l vector3d, \l vector4d
118 \li Enums declared with Q_ENUMS()
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
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:
134 Image { sourceSize: "100x200" }
135 Image { sourceSize: Qt.size(100, 200) }
139 See documentation for each individual type under \l {QML Basic Types} for more
143 \section1 QObject-derived Types
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.
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.
154 \section1 Conversion Between Qt and JavaScript Types
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.
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.)
168 \section2 QVariantList and QVariantMap to JavaScript Array and Object
170 The QML engine provides automatic type conversion between QVariantList and
171 JavaScript arrays, and between QVariantMap and JavaScript objects.
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:
182 \li \snippet qml/qtbinding/variantlistmap/MyItem.qml 0
183 \li \snippet qml/qtbinding/variantlistmap/main.cpp 0
186 This produces output like:
192 Object item: language = QML
193 Object item: released = Tue Sep 21 2010 00:00:00 GMT+1000 (EST)
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++.
202 \section2 QDateTime to JavaScript Date
204 The QML engine provides automatic type conversion between QDateTime values and
205 JavaScript \c Date objects.
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
223 function readDate(dt) {
224 console.log("The given date is:", dt.toUTCString());
233 QQuickView view(QUrl::fromLocalFile("MyItem.qml"));
235 QDateTime dateTime = QDateTime::currentDateTime();
238 QMetaObject::invokeMethod(view.rootObject(), "readDate",
239 Q_RETURN_ARG(QVariant, retValue),
240 Q_ARG(QVariant, QVariant::fromValue(dateTime)));
242 qDebug() << "Value returned from readDate():" << retValue;
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++.
252 \section2 Sequence Type to JavaScript Array
254 Certain C++ sequence types are supported transparently in QML as JavaScript
257 In particular, QML currently supports:
260 \li \c {QList<qreal>}
262 \li \c {QList<QString>} and \c{QStringList}
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.
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
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.
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
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.
299 The default-constructed values for each sequence type are as follows:
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
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)").
314 \section1 Enumeration Types
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
322 class Message : public QObject
326 Q_PROPERTY(Status status READ status NOTIFY statusChanged)
333 Status status() const;
335 void statusChanged();
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:
345 if (status == Message.Ready)
346 console.log("Message is loaded!")
351 \note The names of enum values must begin with a capital letter in order to
352 be accessible from QML.
355 \section2 Enumeration Types as Signal and Method Parameters
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}.
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().
367 For QML signals, enum values may be passed as signal parameters using the \c int
372 signal someOtherSignal(int statusValue)
374 Component.onCompleted: {
375 someOtherSignal(Message.Loading)