read QObject dynamic property in QML ?
-
QObjects allow dynamic properties via
setProperty
andproperty
.Can properties defined/set in this way be read in QML land if that QObject is made available to the QML context?
The code below doesn't work. "myDynamicProp" is undefined in QML land.
Is there a way to do this?
c++
QObject myObj; myObj.setProperty("myDynamicProp", 12345); engine.rootContext()->setContextProperty("myObj", &myObj);
qml
Text { text: myObj.myDynamicProp }
-
QQmlPropertyMap seems to be the best option. its a half-solution.
it has a limitation in that
https://doc.qt.io/qt-5/qqmlpropertymap.html#detailsTo detect value changes made in the UI layer you can connect to the valueChanged() signal. However, note that valueChanged() is NOT emitted when changes are made by calling insert() or clear() - it is only emitted when a value is updated from QML.
I was able to make setting a value trigger a signal to directly trigger qml updates with
class MyQmlPropertyMap : public QQmlPropertyMap { public: MyQmlPropertyMap(); void setValue(QString key, QVariant val) { insert(key, val); auto meta=this->metaObject(); auto propIdx=meta->indexOfProperty(key.toUtf8()); if (propIdx == -1) { return; } auto sigIdx=meta->property(propIdx).notifySignalIndex(); QMetaObject::activate(this, sigIdx, nullptr); } };
-
@poncho524 you could try QQmlPropertyMap
-
QQmlPropertyMap seems to be the best option. its a half-solution.
it has a limitation in that
https://doc.qt.io/qt-5/qqmlpropertymap.html#detailsTo detect value changes made in the UI layer you can connect to the valueChanged() signal. However, note that valueChanged() is NOT emitted when changes are made by calling insert() or clear() - it is only emitted when a value is updated from QML.
I was able to make setting a value trigger a signal to directly trigger qml updates with
class MyQmlPropertyMap : public QQmlPropertyMap { public: MyQmlPropertyMap(); void setValue(QString key, QVariant val) { insert(key, val); auto meta=this->metaObject(); auto propIdx=meta->indexOfProperty(key.toUtf8()); if (propIdx == -1) { return; } auto sigIdx=meta->property(propIdx).notifySignalIndex(); QMetaObject::activate(this, sigIdx, nullptr); } };
-