How to retrieve the value of a QML property from C++?

4.1k views Asked by At

I have the following QQuickItem defined in main.qml.

Flickable {
  id: my_quick
  Accessible.name: "my_quick_item_name"
  objectName: "myquickitem"
  enabled: true

  property real quickProperty: 1.0
}

I get my_quick object in the following way on C++ side.

QQuickItem * my_quick_ptr = QmlEngine_Ptr->rootObjects()[0]->findChild<QQuickItem*>("myquickitem");

How can I get the current value of quickProperty set, into C++ side using my_quick_ptr?

1

There are 1 answers

2
dtech On BEST ANSWER

If you mean QML properties, you can use this approach:

QQmlProperty::read(my_quick_ptr, "quickProperty").toReal()

Using QObject's facilities should also work for QML properties:

my_quick_ptr->property("quickProperty").toReal()

Also, findChild returns a QObject, so you will need to do a safe cast to get a derived pointer from it:

QQuickItem * my_quick_ptr = qobject_cast<QQuickItem *>(QmlEngine_Ptr->rootObjects()[0]->findChild<QQuickItem*>("myquickitem"));
if (my_quick_ptr) // successfully found and cast, can be safely used