How to Bind a QML Property to a C++ Function

From Qt Wiki
Revision as of 15:41, 14 January 2015 by Maintenance script (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Binding a QML property to a C++ function

At the moment Qt Quick does not provide an implementation for linking a QML property to the result of a C++ function. There exists a suggestion for adding support for this here [bugreports.qt.nokia.com] though.

In this article we will show how to make binding of properties to C++ functions work using Q_PROPERTY [doc.qt.nokia.com] with a NOTIFY [doc.qt.nokia.com] signal that is emitted whenever the value of the property changes.

The C++ implementation

In the Object class in the example below we create a Q_PROPERTY that is used to set and update the text in the QML code and that has a changeOfStatus() signal which is emitted whenever the status of the C++ function someFunction() changes:

The Object::getTheChange() function sets the text of the QML item depending on the result of Object::someFunction(). The result is set as the value of the text property in the QML code.

Object::someFunction() is callable from QML as it uses Q_INVOKABLE [doc.qt.nokia.com]. It simply changes the status of a member variable and is called every 5 seconds using a QTimer [doc.qt.nokia.com] to illustrate how the QML property is able to react to the changes of this function. It can also be called from the QML code when clicking the text. At the end it emits the changeOfStatus() signal which triggers Object::getTheChange() to be called and the text to be reevaluated.

main.cpp

The QML implementation

In the QML code below we create a Rectangle [doc.qt.nokia.com] that reacts to mouse clicks. The text is set to the the result of the Object::theChange() function.

main.qml

So, using the approach in the example above, we get a way for QML properties to react to changes that happen internally in the C++ code.

Categories: