How to use a C class declared in a namespace with Q PROPERTY and QML: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
(No difference)

Revision as of 15:49, 14 January 2015

English Български

How to use a C++ class declared in a namespace with Q_PROPERTY and QML

Using a C++ class declared in a namespace with QML works out of the box, in general. All you need to do is to ensure that you register the class for usage in QML with qmlRegisterType() [doc.qt.nokia.com]. When you need to reference the namespaced class in a Q_PROPERTY [doc.qt.nokia.com] however, then there are some concerns that need to be taken for this to work with QML. The example below illustrate the steps that need to be taken.

A Simple Example

The example below consists of 2 classes declared in a namespace:

The Person class is referenced in the Q_PROPERTY declaration of the BirthdayParty class. In order for the QML code using the classes to work as expected, then the namespace name has to be included when referring to the Person class in Q_PROPERTY declarations and in associated read and write function prototypes and also in Q_INVOKABLE [doc.qt.nokia.com] function prototypes. In general, C++ does not have this kind of limitation; it is enough that the class declarations are inside the namespace and there is no need to use namespace names. There is a report in Jira [bugreports.qt.nokia.com] for improving the documentation on this.

C++ implementation

In the C++ code below we ensure that the namespace MyNamespace is listed in front of the class name Person in the read and write functions for the BirthdayParty class below:

main.cpp

If the namespace is removed from these functions, the QML code using the classes will not work as expected.

QML implementation

The example code below shows how the namespaced classes can be used in QML

main.qml

Categories: