diff options
author | Bea Lam <bea.lam@nokia.com> | 2010-04-21 00:58:02 (GMT) |
---|---|---|
committer | Bea Lam <bea.lam@nokia.com> | 2010-04-21 00:59:45 (GMT) |
commit | 61f3cb6e79fea0aed80df091013c2228f64955ec (patch) | |
tree | 916d4879a326739673f918fc340bc5a4c356bcb9 /doc/src/declarative | |
parent | e11a5c4d1a1bb80ac03655227c833b560c7cad3c (diff) | |
download | Qt-61f3cb6e79fea0aed80df091013c2228f64955ec.zip Qt-61f3cb6e79fea0aed80df091013c2228f64955ec.tar.gz Qt-61f3cb6e79fea0aed80df091013c2228f64955ec.tar.bz2 |
Improve docs and examples for Extending QML in C++
Diffstat (limited to 'doc/src/declarative')
-rw-r--r-- | doc/src/declarative/extending.qdoc | 385 |
1 files changed, 202 insertions, 183 deletions
diff --git a/doc/src/declarative/extending.qdoc b/doc/src/declarative/extending.qdoc index d0e5f9e..9844804 100644 --- a/doc/src/declarative/extending.qdoc +++ b/doc/src/declarative/extending.qdoc @@ -43,53 +43,86 @@ \page qml-extending.html \title Extending QML in C++ +The QtDeclarative module provides a set of APIs for extending QML through +C++ extensions. You can write extensions to add your own QML types, extend existing +Qt types, or call C/C++ functions that are not accessible from ordinary QML code. + The QML syntax declaratively describes how to construct an in memory object tree. In Qt, QML is mainly used to describe a visual scene graph, but it is not conceptually limited to this: the QML format is an abstract description of any object tree. All the QML element types included in Qt are implemented using -the C++ extension mechanisms describe on this page. Programmers can use these -APIs to add new types that interact with the existing Qt types, or to repurpose -QML for their own independent use. +the C++ extension mechanisms describe on this page. \tableofcontents \section1 Adding Types \target adding-types +QML can easily be extended to support new types. + +Let's create a new QML type called "Person" that has two properties, a name and a +shoe size. We will make it available in a \l {Modules}{module} called "People", with +a module version of 1.0. We want this \c Person type to be usable from QML like this: + \snippet examples/declarative/extending/adding/example.qml 0 -The QML snippet shown above instantiates one \c Person instance and sets -the name and shoeSize properties on it. Everything in QML ultimately comes down -to either instantiating an object instance, or assigning a property a value. -QML relies heavily on Qt's meta object system and can only instantiate classes -that derive from QObject. +To do this, we need a C++ class that encapsulates this \c Person type and its two +properties. Since QML relies heavily on Qt's \l{Meta-Object System}{meta object system}, +this new class must: + +\list +\o inherit from QObject +\o declare its properties using the Q_PROPERTY() macro +\endlist -The QML engine has no intrinsic knowledge of any class types. Instead the -programmer must define the C++ types, and their corresponding QML name. +Here is the \c Person class: -Custom C++ types are registered using a template function: +\snippet examples/declarative/extending/adding/person.h 0 -\quotation +Now that the \c Person type is defined, it needs to be registered with QML +to make it available to QML code. To do this, call the qmlRegisterType() +template function. For example, this registers the \c Person type as a type called +"Person", to a module named "People", with a module version of 1.0: + +\snippet examples/declarative/extending/adding/main.cpp 0 + +Types can be registered by libraries (as Qt does), application code, +or by plugins (see QDeclarativeExtensionPlugin). + +Now the \c Person type can be used from QML as shown above. When we create a +\c Person item in QML, an instance of the C++ \c Person class is created, and the +\c name and \c shoeSize properties of the \c Person class can be set. All of +the properties of a registered type that are declared with Q_PROPERTY can be used +from QML. + +QML is typesafe. Attempting to assign an invalid value to a property will +generate an error. For example, assuming the name property of the \c Person +element had a type of QString, this would cause an error: \code -template<typename T> -int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName) +Person { + // Will NOT work + name: 12 +} \endcode -Calling qmlRegisterType() registers the C++ type \a T with the QML system, and makes it available in QML -under the name \a qmlName in library \a uri version \a versionMajor.versionMinor. -The \a qmlName can be the same as the C++ type name. +See \l {Extending QML - Adding Types Example} for the complete code used to create +the \c Person type. + +\section2 Interfaces + +QML also supports assigning Qt interfaces. To assign to a property whose type +is a Qt interface pointer, the interface must also be registered with QML. As +they cannot be instantiated directly, registering a Qt interface is different +from registering a new QML type. Instead of registering the type with +qmlRegisterType(), use qmlRegisterInterface(). -Type \a T must be a concrete type that inherits QObject and has a default -constructor. -\endquotation -Types can be registered by libraries (such as Qt does), application code, -or by plugins (see QDeclarativeExtensionPlugin). +\section1 Supporting object and list property types -Once registered, all of the \l {Qt's Property System}{properties} of a supported -type are available for use within QML. QML has intrinsic support for properties -of these types: +When a new type is registered with QML, all of its properties declared with +Q_PROPERTY are available from QML. QML has intrinsic support for properties of +these types: \list \o bool @@ -105,60 +138,36 @@ of these types: \o QVariant \endlist -QML is typesafe. Attempting to assign an invalid value to a property will -generate an error. For example, assuming the name property of the \c Person -element had a type of QString, this would cause an error: +The \c Person type in the previous example had basic property types - a string +for \c name, and an integer for \c shoeSize. However, QML can set properties of +types that are more complex than basic intrinsics like +integers and strings. Properties can also be object pointers, Qt interface +pointers, lists of object pointers, and lists of Qt interface pointers. -\code -Person { - // Will NOT work - name: 12 -} -\endcode +Let's create a new QML type, "BirthdayParty", that has two properties +with more complex types: -\l {Extending QML - Adding Types Example} shows the complete code used to create -the \c Person type. +\list +\o A \c host property whose value is a \c Person item +\o A \c guests property whose value is a list of \c Person items +\endlist -\section1 Object and List Property Types +We want to use it from QML like this: \snippet examples/declarative/extending/properties/example.qml 0 -The QML snippet shown above assigns a \c Person object to the \c BirthdayParty's -celebrant property, and assigns three \c Person objects to the guests property. - -QML can set properties of types that are more complex than basic intrinsics like -integers and strings. Properties can also be object pointers, Qt interface -pointers, lists of object points, and lists of Qt interface pointers. As QML -is typesafe it ensures that only valid types are assigned to these properties, -just like it does for primitive types. +This will assign a \c Person object to the \c BirthdayParty's \c host property, +and assigns three other \c Person objects in a list to the \c guests property. -Properties that are pointers to objects or Qt interfaces are declared with the -Q_PROPERTY() macro, just like other properties. The celebrant property -declaration looks like this: +To do this, we define a \c BirthdayParty class with the two properties. +The \c host property stores a \c Person* pointer. It is declared like this: \snippet examples/declarative/extending/properties/birthdayparty.h 1 -As long as the property type, in this case Person, is registered with QML the -property can be assigned. - -QML also supports assigning Qt interfaces. To assign to a property whose type -is a Qt interface pointer, the interface must also be registered with QML. As -they cannot be instantiated directly, registering a Qt interface is different -from registering a new QML type. The following function is used instead: - -\quotation -\code -template<typename T> -int qmlRegisterInterface(const char *typeName) -\endcode - -Registers the C++ interface \a T with the QML system as \a typeName. - -Following registration, QML can coerce objects that implement this interface -for assignment to appropriately typed properties. -\endquotation +Note the type of the property (\c Person in this case) must be registered with QML with +qmlRegisterType() or qmlRegisterInterface(). Otherwise, the property cannot be assigned in QML. -The guests property is a list of \c Person objects. Properties that are lists +The \c guests property is a list of \c Person* objects. Properties that are lists of objects or Qt interfaces are also declared with the Q_PROPERTY() macro, just like other properties. List properties must have the type \c {QDeclarativeListProperty<T>}. As with object properties, the type \a T must be registered with QML. @@ -167,43 +176,44 @@ The guest property declaration looks like this: \snippet examples/declarative/extending/properties/birthdayparty.h 2 +So, here is the complete \c BirthdayParty class declaration: + +\snippet examples/declarative/extending/properties/birthdayparty.h 0 +\snippet examples/declarative/extending/properties/birthdayparty.h 1 +\snippet examples/declarative/extending/properties/birthdayparty.h 2 +\snippet examples/declarative/extending/properties/birthdayparty.h 3 + +The \c BirthdayClass type is also registered using qmlRegisterType() so +it can be used from QML. + \l {Extending QML - Object and List Property Types Example} shows the complete code used to create the \c BirthdayParty type. \section1 Inheritance and Coercion -\snippet examples/declarative/extending/coercion/example.qml 0 - -The QML snippet shown above assigns a \c Boy object to the \c BirthdayParty's -celebrant property, and assigns three other objects to the guests property. - QML supports C++ inheritance heirarchies and can freely coerce between known, valid object types. This enables the creation of common base classes that allow -the assignment of specialized classes to object or list properties. In the -snippet shown, both the celebrant and the guests properties retain the Person -type used in the previous section, but the assignment is valid as both the Boy -and Girl objects inherit from Person. +the assignment of specialized classes to object or list properties. -To assign to a property, the property's type must have been registered with QML. -Both the qmlRegisterType() and qmlRegisterInterface() template functions already -shown can be used to register a type with QML. Additionally, if a type that acts purely -as a base class that cannot be instantiated from QML needs to be -registered, the following function can be used: +For example, if classes \c Girl and \c Boy both inherit from \c Person, then +\c Girl and \c Boy objects can be assigned in place of \c Person objects, like this: + +\snippet examples/declarative/extending/coercion/example.qml 0 + +To assign to a property, the property's type (in this case, \c Girl and \c Boy) +must be registered with QML. +Both the qmlRegisterType() and qmlRegisterInterface() template functions previously +discussed can be used to register a type with QML. Additionally, in the case of the +\c Person class, which now acts purely as a base class and should no longer be instantiated from QML, +the following function can be used: -\quotation \code template<typename T> int qmlRegisterType() \endcode -Registers the C++ type \a T with the QML system. The parameterless call to the template -function qmlRegisterType() does not define a mapping between the -C++ class and a QML element name, so the type is not instantiable from QML, but -it is available for type coercion. - -Type \a T must inherit QObject, but there are no restrictions on whether it is -concrete or the signature of its constructor. -\endquotation +Calling the parameterless qmlRegisterType() ensures the type is available +to QML for type coercion but cannot be created as a type from QML. QML will automatically coerce C++ types when assigning to either an object property, or to a list property. Only if coercion fails does an assignment @@ -214,71 +224,70 @@ code used to create the \c Boy and \c Girl types. \section1 Default Property -\snippet examples/declarative/extending/default/example.qml 0 +The \e {default property} is a syntactic convenience that allows a type designer to +specify a single property as the type's default. -The QML snippet shown above assigns a collection of objects to the -\c BirthdayParty's default property. +This QML snippet assigns a collection of objects - two \c Boy and one +\c Girl objects - to the \c BirthdayParty's default property: -The default property is a syntactic convenience that allows a type designer to -specify a single property as the type's default. The default property is -assigned to whenever no explicit property is specified. As a convenience, it is -behaviorally identical to assigning the default property explicitly by name. +\snippet examples/declarative/extending/default/example.qml 0 + +The default property is assigned to whenever no explicit property is specified. +As a convenience, it is behaviorally identical to assigning the default property +explicitly by name. From C++, type designers mark the default property using a Q_CLASSINFO() annotation: -\quotation \code -Q_CLASSINFO("DefaultProperty", "property") + Q_CLASSINFO("DefaultProperty", "property") \endcode -Mark \a property as the class's default property. \a property must be either -an object property, or a list property. +The \c property must be either an object property, or a list property. The +\c property can refer to a property declared in the class itself, or a property +inherited from a base class. A default property is optional. A derived class inherits its base class's -default property, but may override it in its own declaration. \a property can -refer to a property declared in the class itself, or a property inherited from a -base class. -\endquotation +default property, but may override it in its own declaration. \l {Extending QML - Default Property Example} shows the complete code used to specify a default property. -\section1 Grouped Properties - -\snippet examples/declarative/extending/grouped/example.qml 1 -The QML snippet shown above assigns a number properties to the \c Boy object, -including four properties using the grouped property syntax. +\section1 Grouped Properties Grouped properties collect similar properties together into a single named block. Grouped properties can be used to present a nicer API to developers, and may also simplify the implementation of common property collections across different types through implementation reuse. +This QML snippet assigns a number properties to the \c Boy object, +including four properties using the grouped property syntax: + +\snippet examples/declarative/extending/grouped/example.qml 1 + A grouped property block is implemented as a read-only object property. The shoe property shown is declared like this: \snippet examples/declarative/extending/grouped/person.h 1 -The ShoeDescription type declares the properties available to the grouped -property block - in this case the size, color, brand and price properties. +The \c ShoeDescription type declares the properties available to the grouped +property block - in this case the \c size, \c color, \c brand and \c price properties. -Grouped property blocks may declared and accessed be recusively. +Grouped property blocks may be declared and accessed recusively. \l {Extending QML - Grouped Properties Example} shows the complete code used to implement the \c shoe property grouping. \section1 Attached Properties -\snippet examples/declarative/extending/attached/example.qml 1 +Attached properties allow unrelated types to annotate other types with some +additional properties, generally for their own use. This QML snippet assigns +an \c rsvp property using the attached property syntax: -The QML snippet shown above assigns the rsvp property using the attached -property syntax. +\snippet examples/declarative/extending/attached/example.qml 1 -Attached properties allow unrelated types to annotate other types with some -additional properties, generally for their own use. Attached properties are -identified through the use of the attacher type name, in the case shown +Attached properties are identified through the use of the attacher type name; in the case shown \c BirthdayParty, as a suffix to the property name. In the example shown, \c BirthdayParty is called the attaching type, and the @@ -289,35 +298,36 @@ QObject derived type, called the attachment object. The properties on the attachment object are those that become available for use as the attached property block. -Any QML type can become an attaching type by declaring the +Any QML type can become an attaching type by declaring a \c qmlAttachedProperties() public function and declaring that the class has QML_HAS_ATTACHED_PROPERTIES: -\quotation \code -class MyType : public QObject { - Q_OBJECT -public: + class MyType : public QObject { + Q_OBJECT + public: - ... + ... - static AttachedPropertiesType *qmlAttachedProperties(QObject *object); -}; + static AttachedPropertiesType *qmlAttachedProperties(QObject *object); + }; -QML_DECLARE_TYPEINFO(MyType, QML_HAS_ATTACHED_PROPERTIES) + QML_DECLARE_TYPEINFO(MyType, QML_HAS_ATTACHED_PROPERTIES) \endcode -Return an attachment object, of type \a AttachedPropertiesType, for the + +The qmlAttachedProperties() method returns an attachment object, of type \a AttachedPropertiesType, for the attachee \a object instance. It is customary, though not strictly required, for the attachment object to be parented to \a object to prevent memory leaks. -\a AttachedPropertiesType must be a QObject derived type. The properties on +The returned \a AttachedPropertiesType must be a QObject derived type. The properties on this type will be accessible through the attached properties syntax. -This method will be called at most once for each attachee object instance. The +This method is called at most once for each attachee object instance. The QML engine will cache the returned instance pointer for subsequent attached property accesses. Consequently the attachment object may not be deleted until \a object is destroyed. -\endquotation + +\section2 Use of attached properties Conceptually, attached properties are a \e type exporting a set of additional properties that can be set on \e any other object instance. Attached properties @@ -326,15 +336,18 @@ their effect may be so limited. For example, a common usage scenario is for a type to enhance the properties available to its children in order to gather instance specific data. Here we -add a rsvp field to all the guests coming to a birthday party: +add a \c rsvp field to all the guests coming to a birthday party: + \code BirthdayParty { Boy { BirthdayParty.rsvp: "2009-06-01" } } \endcode + However, as a type cannot limit the instances to which the attachment object must attach, the following is also allowed, even though adding a birthday party rsvp in this context will have no effect. + \code GraduationParty { Boy { BirthdayParty.rsvp: "2009-06-01" } @@ -362,7 +375,7 @@ implement the rsvp attached property. \section1 Memory Management and QVariant types -It is an elements responsibility to ensure that it does not access or return +It is an element's responsibility to ensure that it does not access or return pointers to invalid objects. QML makes the following guarentees: \list @@ -393,21 +406,24 @@ this situation, but it must not crash. \section1 Signal Support -\snippet examples/declarative/extending/signal/example.qml 0 -\snippet examples/declarative/extending/signal/example.qml 1 - -The QML snippet shown above associates the evaluation of a JavaScript expression -with the emission of a Qt signal. - All Qt signals on a registered class become available as special "signal properties" within QML to which the user can assign a single JavaScript expression. The signal property's name is a transformed version of the Qt signal name: "on" is prepended, and the first letter of the signal name upper -cased. For example, the signal used in the example above has the following -C++ signature: +cased. + +For example, if the \c BirthdayParty class has a signal like this: \snippet examples/declarative/extending/signal/birthdayparty.h 0 +This signal can be connected to from QML like this: + +\snippet examples/declarative/extending/signal/example.qml 0 +\snippet examples/declarative/extending/signal/example.qml 1 + +This associates the evaluation of a JavaScript expression +with the emission of a Qt signal. + In classes with multiple signals with the same name, only the final signal is accessible as a signal property. Note that signals with the same name but different parameters cannot be distinguished. @@ -424,38 +440,35 @@ implement the onPartyStarted signal property. \section1 Property Value Sources -\snippet examples/declarative/extending/valuesource/example.qml 0 -\snippet examples/declarative/extending/valuesource/example.qml 1 - -The QML snippet shown above applies a property value source to the speaker property. -A property value source generates a value for a property that changes over time. +A property value source is an element that generates a value for a +property that changes over time. Property value sources are most commonly used to +create animations; QML's built-in \l {Behavior}{Behavior} and various +\l {QML Animation}{animation} elements are actually property value sources. -Property value sources are most commonly used to do animation. Rather than -constructing an animation object and manually setting the animation's "target" -property, a property value source can be assigned directly to a property of any -type and automatically set up this association. +The \c BirthdayParty class has an \c announcement string property +whose value is printed to the console whenever it changes. Using a property value +source called \c HappyBirthdaySong, the value of this property can be changed, +over time, to each lyric in the song "Happy Birthday". For further customization, +a \c name property allows the song lyrics to be personalized with a particular name. +The \c HappyBirthdaySong property value source would be used in QML like this: -The example shown here is rather contrived: the speaker property of the -BirthdayParty object is a string that is printed every time it is assigned and -the HappyBirthday value source generates the lyrics of the song -"Happy Birthday". - -\snippet examples/declarative/extending/valuesource/birthdayparty.h 0 +\snippet examples/declarative/extending/valuesource/example.qml 0 +\snippet examples/declarative/extending/valuesource/example.qml 1 -Normally, assigning an object to a string property would not be allowed. In +(Normally, assigning an object to a string property would not be allowed. In the case of a property value source, rather than assigning the object instance itself, the QML engine sets up an association between the value source and -the property. +the property.) Property value sources are special types that derive from the QDeclarativePropertyValueSource base class. This base class contains a single method, QDeclarativePropertyValueSource::setTarget(), that the QML engine invokes when -associating the property value source with a property. The relevant part of -the HappyBirthday type declaration looks like this: +associating the property value source with a property. Here is the relevant part of +the \c HappyBirthdaySong type declaration: -\snippet examples/declarative/extending/valuesource/happybirthday.h 0 -\snippet examples/declarative/extending/valuesource/happybirthday.h 1 -\snippet examples/declarative/extending/valuesource/happybirthday.h 2 +\snippet examples/declarative/extending/valuesource/happybirthdaysong.h 0 +\snippet examples/declarative/extending/valuesource/happybirthdaysong.h 1 +\snippet examples/declarative/extending/valuesource/happybirthdaysong.h 2 In all other respects, property value sources are regular QML types. They must be registered with the QML engine using the same macros as other types, and can @@ -463,20 +476,15 @@ contain properties, signals and methods just like other types. When a property value source object is assigned to a property, QML first tries to assign it normally, as though it were a regular QML type. Only if this -assignment fails does the engine call the setTarget() method. This allows +assignment fails does the engine call the +\l {QDeclarativePropertyValueSource::setTarget()}{setTarget()} method. This allows the type to also be used in contexts other than just as a value source. \l {Extending QML - Property Value Source Example} shows the complete code used -implement the HappyBirthday property value source. +implement the HappyBirthdaySong property value source. \section1 Property Binding -\snippet examples/declarative/extending/binding/example.qml 0 -\snippet examples/declarative/extending/binding/example.qml 1 - -The QML snippet shown above uses a property binding to ensure the -HappyBirthday's name property remains up to date with the celebrant. - Property binding is a core feature of QML. In addition to assigning literal values, property bindings allow the developer to assign an arbitrarily complex JavaScript expression that may include dependencies on other property values. @@ -488,15 +496,23 @@ All properties on custom types automatically support property binding. However, for binding to work correctly, QML must be able to reliably determine when a property has changed so that it knows to reevaluate any bindings that depend on the property's value. QML relies on the presence of a -\c {Qt's Property System}{NOTIFY signal} for this determination. +\l {Qt's Property System}{NOTIFY signal} for this determination. -Here is the celebrant property declaration: +For example, to enable property binding for the \c host property in \c BirthdayParty, +add a \c hostChanged signal that is emitted when the \c host value changes, and +declare the \c host property like this: \snippet examples/declarative/extending/binding/birthdayparty.h 0 -The NOTIFY attribute is followed by a signal name. It is the responsibility of -the class implementer to ensure that whenever the property's value changes, the -NOTIFY signal is emitted. The signature of the NOTIFY signal is not important to QML. +This enables the use of a property binding to ensure the \c name value of the +\c HappyBirthdaySong is updated if the \c host value changes: + +\snippet examples/declarative/extending/binding/example.qml 0 +\snippet examples/declarative/extending/binding/example.qml 1 + +It is the responsibility of the class implementer to ensure that whenever the +property's value changes, the associated NOTIFY signal is emitted. The +signature of the NOTIFY signal is not important to QML. To prevent loops or excessive evaluation, developers should ensure that the signal is only emitted whenever the property's value is actually changed. If @@ -504,6 +520,8 @@ a property, or group of properties, is infrequently used it is permitted to use the same NOTIFY signal for several properties. This should be done with care to ensure that performance doesn't suffer. +\section2 Use of notify signals + To keep QML reliable, if a property does not have a NOTIFY signal, it cannot be used in a binding expression. However, the property can still be assigned a binding as QML does not need to monitor the property for change in that @@ -543,11 +561,6 @@ include NOTIFY signals for use in binding. \section1 Extension Objects -\snippet examples/declarative/extending/extended/example.qml 0 - -The QML snippet shown above adds a new property to an existing C++ type without -modifying its source code. - When integrating existing classes and technology into QML, their APIs will often need to be tweaked to fit better into the declarative environment. Although the best results are usually obtained by modifying the original classes @@ -561,6 +574,11 @@ type definition allows the programmer to supply an additional type - known as th extension type - when registering the target class whose properties are transparently merged with the original target class when used from within QML. +Here is a QML snippet that adds a new property to an existing C++ type without +modifying its source code: + +\snippet examples/declarative/extending/extended/example.qml 0 + An extension class is a regular QObject, with a constructor that takes a QObject pointer. When needed (extension classes are delay created until the first extended property is accessed) the extension class is created and the target object is @@ -572,6 +590,7 @@ When an extended type is installed, one of the #define QML_REGISTER_EXTENDED_TYPE(URI, VMAJ, VFROM, VTO, QDeclarativeName,T, ExtendedT) #define QML_REGISTER_EXTENDED_NOCREATE_TYPE(T, ExtendedT) \endcode + macros should be used instead of the regular \c QML_REGISTER_TYPE or \c QML_REGISTER_NOCREATE_TYPE. The arguments are identical to the corresponding non-extension object macro, except for the ExtendedT parameter which is the type |