1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
28 \page qtqml-cppintegration-data.html
29 \title Exposing Data from C++ to QML
30 \brief Description of how to expose data from C++ to QML
33 // XXX TODO The content of "Exposing C++ Functionality To QML" and
34 // "Exposing Data From C++ To QML" should probably be grouped together
35 // on the same page, or separated in a more distinct way.
36 // [CA]: I'm not so sure. Functions vs Data is separate and distinct.
37 // I like the separation of pages, to be honest.
40 \section1 Ownership Semantics
42 The ownership of data transferred from C++ to QML always remains with C++ in all
43 cases, except for one (where a QObject is returned from a method invocation).
44 More information about that possible ownership change is included
45 below. Furthermore, QML respects the normal QObject parent ownership
46 semantics of Qt C++, and won't ever take ownership of a QObject which
49 \section1 Context Properties
51 Data from C++ may be exposed to QML via context properties.
52 Since all expressions evaluated in QML are evaluated in a
53 particular context, if the context is modified, all bindings
54 in that context will be re-evaluated, and thus this method
55 should be used with care (or only during initialization).
57 \section1 Instance Property Access
59 Data from a registered C++ type may be exposed as a property
60 which has been declared using the Q_PROPERTY macro. Such a
61 property will be accessible from QML code.
65 \target properties-cpp
67 Any \l {The Property System}{Qt properties} - that is, those declared with the Q_PROPERTY()
68 macro - are accessible from QML. Here is a modified version of the \l {Embedding C++ objects into
69 QML components}{earlier example} on this page; here, the \c ApplicationData class has a \c backgroundColor
70 property. This property can be written to and read from QML:
74 \li \snippet qml/qtbinding/properties-cpp/applicationdata.h 0
75 \li \snippet qml/qtbinding/properties-cpp/MyItem.qml 0
78 Notice the \c backgroundColorChanged signal is declared as the NOTIFY signal for the
79 \c backgroundColor property. If a Qt property does not have an associated NOTIFY signal,
80 the property cannot be used for \l{Property Binding}, as the QML engine would not be
81 notified when the value changes. If you are using custom types in QML, make sure their
82 properties have NOTIFY signals so that they can be used in property bindings.
84 See \l {Tutorial: Extending QML with C++} for further details and examples
85 on using Qt properties with QML.
90 \section1 Supported Data Types
92 Any C++ data that is used from QML - whether as custom properties, or parameters for signals or
93 functions - must be of a type that is recognizable by QML.
95 By default, QML recognizes the following data types:
97 // XXX TODO This list should refer to "QML Basic Types" list to refer to the type conversions
101 \li unsigned int, int
102 \li float, double, qreal
106 \li QDate, QTime, QDateTime
111 \li QVariantList, QVariantMap
113 \li Enumerations declared with Q_ENUMS()
116 To allow a custom C++ type to be created or used in QML, the C++ class must be registered as a QML
117 type using qmlRegisterType(), as shown in the \l {Defining new QML elements} section above.
122 \section2 JavaScript Arrays and Objects
124 There is built-in support for automatic type conversion between QVariantList and JavaScript
125 arrays, and QVariantMap and JavaScript objects.
127 For example, the function defined in QML below left expects two arguments, an array and an object, and prints
128 their contents using the standard JavaScript syntax for array and object item access. The C++ code
129 below right calls this function, passing a QVariantList and a QVariantMap, which are automatically
130 converted to JavaScript array and object values, repectively:
138 \li \snippet qml/qtbinding/variantlistmap/MyItem.qml 0
139 \li \snippet qml/qtbinding/variantlistmap/main.cpp 0
142 This produces output like:
148 Object item: language = QML
149 Object item: released = Tue Sep 21 2010 00:00:00 GMT+1000 (EST)
152 Similarly, if a C++ type uses a QVariantList or QVariantMap type for a property or method
153 parameter, the value can be created as a JavaScript array or object in the QML
154 side, and is automatically converted to a QVariantList or QVariantMap when it is passed to C++.
157 \section2 Using Enumerations of a Custom Type
159 To use an enumeration from a custom C++ component, the enumeration must be declared with Q_ENUMS() to
160 register it with Qt's meta object system. For example, the following C++ type has a \c Status enum:
162 \snippet qml/qtbinding/enums/imageviewer.h start
163 \snippet qml/qtbinding/enums/imageviewer.h end
165 Providing the \c ImageViewer class has been registered using qmlRegisterType(), its \c Status enum can
166 now be used from QML:
168 \snippet qml/qtbinding/enums/standalone.qml 0
170 The C++ type must be registered with QML to use its enums. If your C++ type is not instantiable, it
171 can be registered using qmlRegisterUncreatableType(). To be accessible from QML, the names of enum values
172 must begin with a capital letter.
174 See the \l {Tutorial: Extending QML with C++}{Writing QML extensions with C++} tutorial and
175 the \l{Extending QML with C++} reference documentation for
179 \section2 Using Enumeration Values as Signal and Method Parameters
181 C++ signals may pass enumeration values as signal parameters to QML, providing that the enumeration
182 and the signal are declared within the same class, or that the enumeration value is one of those declared
183 in the \l {Qt}{Qt Namespace}.
185 Likewise, invokable C++ method parameters may be enumeration values providing
186 that the enumeration and the method are declared within the same class, or that
187 the enumeration value is one of those declared in the \l {Qt}{Qt Namespace}.
189 Additionally, if a C++ signal with an enum parameter should be connectable to a QML function using the
190 \l{QML Signal and Handler Event System#Connecting Signals to Methods and Signals}{connect()}
191 function, the enum type must be registered using qRegisterMetaType().
193 For QML signals, enum values may be used as signal parameters using the \c int type:
195 \snippet qml/qtbinding/enums/standalone.qml 1
200 \section2 Automatic Type Conversion from Strings
202 As a convenience, some basic types can be specified in QML using format strings to make it easier to
203 pass simple values from QML to C++.
212 \li Color name, "#RRGGBB", "#RRGGBBAA"
213 \li "red", "#ff0000", "#ff000000"
224 \li "x,y,WidthxHeight"
237 \li "http://www.example.com"
243 \li Enumeration value
248 (More details on these string formats and types can be found in the
249 \l {QML Basic Types}{basic type documentation}.)
251 These string formats can be used to set QML \c property values and pass arguments to C++
252 functions. This is demonstrated by various examples on this page; in the above
253 \l{#properties-cpp}{Qt properties example}, the \c ApplicationData class has a \c backgroundColor
254 property of a QColor type, which is set from the QML code with the string "red" rather rather
255 than an actual QColor object.
257 If it is preferred to pass an explicitly-typed value rather than a string, the global
258 \l{QmlGlobalQtObject}{Qt object} provides convenience functions for creating some of the object
259 types listed above. For example, \l{QML:Qt::rgba()}{Qt.rgba()} creates a QColor value from four
260 RGBA values. The QColor returned from this function could be used instead of a string to set
261 a QColor-type property or to call a C++ function that requires a QColor parameter.
266 \section1 Data Returned from Instance Method Invocation
268 A registered C++ type may have functions flagged with the
269 Q_INVOKABLE flag defined. Those functions of an instance of
270 such a type will be accessible from QML. The function may
271 have a return value, which will be converted to a JavaScript
272 value when accessed from a JavaScript expression in QML.
274 Note that if the return value is a QObject pointer (or a
275 pointer to a QObject-derived type), the QML engine will assume
276 ownership of it unless the object has had its ownership previously
277 explicitly set (to QQmlEngine::CppOwnership).
283 \section2 Embedding C++ Objects into QML Components
285 When loading a QML scene into a C++ application, it can be useful to directly embed C++ data into
286 the QML object. QQmlContext enables this by exposing data to the context of a QML
287 component, allowing data to be injected from C++ into QML.
289 For example, here is a QML item that refers to a \c currentDateTime value that does not exist in
292 \snippet qml/qtbinding/context/MyItem.qml 0
294 This \c currentDateTime value can be set directly by the C++ application that loads the QML
295 component, using QQmlContext::setContextProperty():
297 \snippet qml/qtbinding/context/main.cpp 0
299 Context properties can hold either QVariant or QObject* values. This means custom C++ objects can
300 also be injected using this approach, and these objects can be modified and read directly in QML.
301 Here, we modify the above example to embed a QObject instance instead of a QDateTime value, and the QML code
302 invokes a method on the object instance:
307 \snippet qml/qtbinding/context-advanced/applicationdata.h 0
309 \snippet qml/qtbinding/context-advanced/main.cpp 0
311 \snippet qml/qtbinding/context-advanced/MyItem.qml 0
314 (Note that date/time values returned from C++ to QML can be formatted through
315 \l{QML:Qt::formatDateTime}{Qt.formatDateTime()} and associated functions.)
317 If the QML item needs to receive signals from the context property, it can connect to them using the
318 \l Connections element. For example, if \c ApplicationData has a signal named \c
319 dataChanged(), this signal can be connected to using an \c onDataChanged handler within
320 a \l Connections object:
322 \snippet qml/qtbinding/context-advanced/connections.qml 0
324 Context properties can be useful for using C++ based data models in a QML view. See the
325 \l {quick/modelviews/stringlistmodel}{String ListModel},
326 \l {quick/modelviews/objectlistmodel}{Object ListModel} and
327 \l {quick/modelviews/abstractitemmodel}{AbstractItemModel} models for
328 respective examples on using QStringListModel, QObjectList-based models and QAbstractItemModel
331 Also see the QQmlContext documentation for more information.
338 \section1 Exposing Qt C++ Properties
340 The \l{QQmlEngine}{QML engine} utilizes Qt's
341 \l{The Property System}{Property System} and in effect, QML
342 \l{Property Binding}{property bindings} also use Qt properties.
344 Essentially, a Qt C++ property has a \e write function, \e read function,
345 and has a signal function. QML properties are inheritely public, both
346 readable and writable, albeit type-safe. QML properties may also have
347 signals which are emitted when the property value or binding changes.
349 The QML property equivalent of a Qt C++ property is created as a property
350 with the \l Q_PROPERTY() macro. There needs to be C++ functions assigned as
351 the property's read, write, and signal handler function.
353 The \l {Creating QML Object Types from C++}{Register a Type} section mentions that the
354 \c Person class has properties that are exposed to the QML context. The QML
355 properties are created with the \c Q_PROPERTY macro. The macro associates
356 the properties to the read, write, and singal functions in its argument.
359 Q_PROPERTY(int size READ size WRITE setSize NOTIFY shoeChanged)
362 A \c Shoe class might have an integer property called \c size. We set the \c
363 size() function as the \c READ function and the \c setSize() function to be
364 the \c WRITE function. In a QML application, when a property is read, the \c
365 size() is called and when the property's binding changes, the \c setSize()
366 is called. The READ function, by definition, must return the same type as
369 We may also connect a \l{signals and slots}{signal} to a property. The \c
370 size property may have a \c shoeChanged signal indicated after the \c NOTIFY
371 parameter of the macro. The \c shoeChanged becomes a \l{QML Signal and
372 Handler Event System}{QML signal} and the runtime will create QML handler
373 called \c onShoeChanged. Whenever the size property's binding changes, the
374 \c shoeChanged signal is emitted and the \c onShoeChanged handler is
375 invoked. In the handler, commands such as \l{JavaScript Expressions in
376 QML}{JavaScript expressions} can perform clean-up operations or call other
379 \b{Note:} The QML signal handler will always be named
380 on<Property-name>Changed, regardless of the name used for the NOTIFY
381 signal in C++. We recommend using <property-name>Changed() for the
382 NOTIFY signal in C++.
384 We may also make the property a \c read-only property by placing
385 \c CONSTANT in the parameter. Changing the binding will generate an error.
387 //A read-only property
388 Q_PROPERTY(int size READ size CONSTANT)
391 \section2 Default Property
393 When imported, QML components will bind their children to their designated
394 \l{default-property}{default property}. This is helpful, for example,
395 to redirect any declared child components to a property of another
398 The runtime can set a property to be the default property by tagging the
399 property with \c DefaultProperty in The Q_CLASSINFO() macro.
402 Q_CLASSINFO("DefaultProperty", "pipe")
405 The property tagged as default property, \c pipe, can only be an object
406 property, or a list property.
408 A default property is optional. A derived class inherits its base class's
409 default property, but may override it in its own declaration. The \c pipe
410 property can refer to a property declared in the class itself, or a property
411 inherited from a base class.
413 The \l{Extending QML - Default Property Example}{Default Properties} example
414 uses \l{default-property}{default properties} to assign the children of
415 a component to a specific property.
417 \section2 Grouped Properties
419 A property group may be functionally defined as a set of related properties.
420 For example, the \l{Layouts with Anchors}{anchors} are a group of
421 related properties. In practice, property groups resemble a parent object
422 where the individual properties are accessed as children.
424 A grouped property's member properties are accessed using the
425 <group>.<property> notation. For example, shoe.color is the way to access
426 the \c color property in the \c shoe property group .
428 \snippet examples/qml/cppextensions/referenceexamples/grouped/example.qml ungrouped
430 Alternatively, the group can be accessed as a set.
431 \snippet examples/qml/cppextensions/referenceexamples/grouped/example.qml grouped
433 A grouped property block is implemented as a read-only object property. The
434 \c shoe property shown is declared like this:
436 \snippet examples/qml/cppextensions/referenceexamples/grouped/person.h 1
438 The \c ShoeDescription type declares the properties available to the grouped
439 property block - in this case the \c size, \c color, \c brand and \c price properties.
441 Grouped property blocks may declared and accessed be recusively.
443 \l {Extending QML - Grouped Properties Example} shows the complete code used to
444 implement the \c shoe property grouping.
446 \section2 Attached Properties
448 Attached properties annotate or add properties to another type or component.
449 For example, the \l Keys \e{attaching type} contains \e{attached properties}
450 that other elements may use to respond to key input. Conceptually, attached
451 properties are a \e type exporting a set of additional properties that can
452 be set on any other object instance.
454 The attaching type is a QObject derived type. The properties on the
455 attaching type are those that become available for use as attached
458 \snippet examples/qml/cppextensions/referenceexamples/attached/example.qml 1
460 The \c BirthdayParty is called the attaching type and the
461 \c Boy instance the attachee object instance. The property \c rsvp is the
464 Any Qt C++ type can become an attaching type by declaring the \c
465 qmlAttachedProperties() a public member function and declaring that the
466 class has QML_HAS_ATTACHED_PROPERTIES.
469 static AttachedPropertiesType *qmlAttachedProperties(QObject *object);
472 This static pointer returns an attachment object, of type \a
473 AttachedPropertiesType, for the attachee \a object instance. It is
474 customary, though not strictly required, for the attachment object to be
475 parented to \a object to prevent memory leaks.
476 The \l {Extending QML - Attached Properties Example}{Birthday}
477 class has \c BirthdayPartyAttached attached properties.
479 \snippet examples/qml/cppextensions/referenceexamples/attached/birthdayparty.h static attached
481 The QML_DECLARE_TYPEINFO() macro can notify the runtime that the type has
482 attached properties with the QML_HAS_ATTACHED_PROPERTIES argument.
484 \snippet examples/qml/cppextensions/referenceexamples/attached/birthdayparty.h declare attached
486 The qmlAttachedProperties method will be called at most once for each
487 attachee object instance. The QML engine will cache the returned instance
488 pointer for subsequent attached property accesses. Consequently the
489 attachment object may not be deleted until \a object is destroyed.
491 A common usage scenario is for a type to enhance the properties
492 available to its children in order to gather instance specific data.
494 \snippet examples/qml/cppextensions/referenceexamples/attached/example.qml begin
495 \snippet examples/qml/cppextensions/referenceexamples/attached/example.qml rsvp
496 \snippet examples/qml/cppextensions/referenceexamples/attached/example.qml end
498 However, as a QML type cannot limit the instances to which the attachment
499 object must attach, the following is also allowed, even though adding a
500 birthday party rsvp in this context will have no effect. Instead, \c
501 BirthdayParty could be a separate component with a property \c rsvp.
504 Boy { BirthdayParty.rsvp: "2009-06-01" }
508 From C++, including the attaching type implementation, the attachment object
509 for an instance can be accessed using the following method:
513 QObject *qmlAttachedPropertiesObject<T>(QObject *attachee, bool create = true);
516 This returns the attachment object attached to \a attachee by the attaching
517 type \a T. If type \a T is not a valid attaching type, this method always
518 returns 0. If \a create is true, a valid attachment object will always be
519 returned, creating it if it does not already exist. If \a create is false,
520 the attachment object will only be returned if it has previously been
523 The \c rsvp properties of each guest in the \c Birthday party is accessible
524 through the \c qmlAttachedPropertiesObject function.
526 \snippet examples/qml/cppextensions/referenceexamples/attached/main.cpp query rsvp
529 \l {Extending QML - Attached Properties Example}{Attached Properties Example}
530 demonstrates the creation of attached properties with a birthday party
533 \section2 Object and List Properties
535 QML can set properties of types that are more complex than basic intrinsics like
536 integers and strings. Properties can also be object pointers, Qt interface
537 pointers, lists of object pointers, and lists of Qt interface pointers. As QML
538 is typesafe it ensures that only valid types are assigned to these properties,
539 just like it does for primitive types.
541 Properties that are pointers to objects or Qt interfaces are declared with the
542 Q_PROPERTY() macro, just like other properties. The \c host property
543 declaration looks like this:
545 \snippet examples/qml/cppextensions/referenceexamples/properties/birthdayparty.h 1
547 As long as the property type, in this case \c Person, is registered with QML the
548 property can be assigned.
550 QML also supports assigning Qt interfaces. To assign to a property whose type
551 is a Qt interface pointer, the interface must also be registered with QML. As
552 they cannot be instantiated directly, registering a Qt interface is different
553 from registering a new QML type. The following function is used instead:
557 int qmlRegisterInterface(const char *typeName)
560 \c qmlRegisterInterface registers the C++ interface \a T with the QML system
563 Following registration, QML can coerce objects that implement this interface
564 for assignment to appropriately typed properties.
567 \snippet examples/qml/cppextensions/referenceexamples/properties/example.qml 0
569 The \c guests property is a \e{list property} of \c Person objects. A list
570 of \c Person objects are bound to the \c BirthdayParty's \c host property,
571 and assigns three \c Person objects to the guests property.
573 Properties that are lists of objects or Qt interfaces are also declared with
574 the Q_PROPERTY() macro. However, list properties must have the type
575 \l{QQmlListProperty}{QQmlListProperty<T>}.
577 \snippet examples/qml/cppextensions/referenceexamples/properties/birthdayparty.h 2
579 As with the other property types, the type of list content, \a T, must be
580 \l{Creating QML Object Types from C++}{registered} into the runtime.
582 \snippet examples/qml/cppextensions/referenceexamples/properties/main.cpp register list
584 \l {Extending QML - Object and List Property Types Example} shows the
585 complete code used to create the \c BirthdayParty type. For more
586 information, visit \l{QQmlListProperty}{QQmlListProperty<T>}
587 for creating list properties.
589 \section2 Sequence Types
591 Certain C++ sequence types are supported transparently in QML as JavaScript
593 In particular, QML currently supports:
596 \li \c {QList<qreal>}
598 \li \c {QList<QString>} and \c{QStringList}
602 These sequence types are implemented directly in terms of the underlying C++
603 sequence. There are two ways in which such sequences can be exposed to QML:
604 as a Q_PROPERTY of the given sequence type; or as the return type of a
605 Q_INVOKABLE method. There are some differences in the way these are
606 implemented, which are important to note.
608 If the sequence is exposed as a Q_PROPERTY, accessing any value in the
609 sequence by index will cause the sequence data to be read from the QObject's
610 property, then a read to occur. Similarly, modifying any value in the
611 sequence will cause the sequence data to be read, and then the modification
612 will be performed and the modified sequence will be written back to the
615 If the sequence is returned from a Q_INVOKABLE function, access and mutation
616 is much cheaper, as no QObject property read or write occurs; instead, the
617 C++ sequence data is accessed and modified directly.
619 Other sequence types are not supported transparently, and instead an
620 instance of any other sequence type will be passed between QML and C++ as an
623 \b {Important Note:} There are some minor differences between the
624 semantics of such sequence Array types and default JavaScript Array types
625 which result from the use of a C++ storage type in the implementation. In
626 particular, deleting an element from an Array will result in a
627 default-constructed value replacing that element, rather than an Undefined
628 value. Similarly, setting the length property of the Array to a value larger
629 than its current value will result in the Array being padded out to the
630 specified length with default-constructed elements rather than Undefined
631 elements. Finally, the Qt container classes support signed (rather than
632 unsigned) integer indexes; thus, attempting to access any index greater
633 than INT_MAX will fail.
635 The default-constructed values for each sequence type are as follows:
637 \row \li QList<int> \li integer value 0
638 \row \li QList<qreal> \li real value 0.0
639 \row \li QList<bool> \li boolean value \c {false}
640 \row \li QList<QString> and QStringList \li empty QString
641 \row \li QList<QUrl> \li empty QUrl
644 If you wish to remove elements from a sequence rather than simply replace
645 them with default constructed values, do not use the indexed delete operator
646 ("delete sequence[i]") but instead use the \c {splice} function
647 ("sequence.splice(startIndex, deleteCount)").
652 \section1 Property Value Sources
654 \snippet examples/qml/cppextensions/referenceexamples/valuesource/example.qml 0
655 \snippet examples/qml/cppextensions/referenceexamples/valuesource/example.qml 1
657 The QML snippet shown above applies a property value source to the \c announcement property.
658 A property value source generates a value for a property that changes over time.
660 Property value sources are most commonly used to do animation. Rather than
661 constructing an animation object and manually setting the animation's "target"
662 property, a property value source can be assigned directly to a property of any
663 type and automatically set up this association.
665 The example shown here is rather contrived: the \c announcement property of the
666 \c BirthdayParty object is a string that is printed every time it is assigned and
667 the \c HappyBirthdaySong value source generates the lyrics of the song
670 \snippet examples/qml/cppextensions/referenceexamples/valuesource/birthdayparty.h 0
672 Normally, assigning an object to a string property would not be allowed. In
673 the case of a property value source, rather than assigning the object instance
674 itself, the QML engine sets up an association between the value source and
677 Property value sources are special types that derive from the
678 QQmlPropertyValueSource base class. This base class contains a single method,
679 QQmlPropertyValueSource::setTarget(), that the QML engine invokes when
680 associating the property value source with a property. The relevant part of
681 the \c HappyBirthdaySong type declaration looks like this:
683 \snippet examples/qml/cppextensions/referenceexamples/valuesource/happybirthdaysong.h 0
684 \snippet examples/qml/cppextensions/referenceexamples/valuesource/happybirthdaysong.h 1
685 \snippet examples/qml/cppextensions/referenceexamples/valuesource/happybirthdaysong.h 2
687 In all other respects, property value sources are regular QML types. They must
688 be registered with the QML engine using the same macros as other types, and can
689 contain properties, signals and methods just like other types.
691 When a property value source object is assigned to a property, QML first tries
692 to assign it normally, as though it were a regular QML type. Only if this
693 assignment fails does the engine call the \l {QQmlPropertyValueSource::}{setTarget()} method. This allows
694 the type to also be used in contexts other than just as a value source.
696 \l {Extending QML - Property Value Source Example} shows the complete code used
697 to implement the \c HappyBirthdaySong property value source.