Access read-only C++ property from QML
-
I have defined a C++ class SharedConstants, which contains a Q_PROPERTY constant QString value. I want to read this property but not write it from QML.
Here is my C++ class:
/// Constants shared between C++ and QML code class SharedConstants : public QObject { Q_OBJECT public: /// Define read-only QString property called "testString" Q_PROPERTY(QString testString READ getTestString) /// Just return a dummy string for now... QString getTestString() const { std::cout << "**** getTestString()\n"; return QString("Dummy value"); } };
Here is my QML:
ApplicationWindow { [...] property string testString: SharedConstants.testString Component.onCompleted: {console.log("onCompleted"); console.log("testString: ", testString)}
So I expect testString = “Dummy value” in the QML.
I find that QML can access testString from QML if I set a SharedConstant instance as a context property instead of registering it - i.e. in main.cpp:
SharedConstants constants; engine.rootContext()->setContextProperty("SharedConstants", &constants);
QML output:
qml: testString: Dummy valueBut I will be adding other stuff to SharedConstants (e.g. enum) so I must actually register SharedConstants (as described here) in main.cpp:
// Register SharedConstants so QML can access its properties qmlRegisterType<SharedConstants>("SharedConstants", 1, 0, "SharedConstants");
(and I add "import SharedConstants 1.0" to the QML file.)
But now the QString testString is blank/null when accessed from QML :qml: testString:
Debugging shows that the designated C++ accessor function getTestString() is not invoked either.
What am I doing wrong here?Thanks!
-
@Tom-asso said in Access read-only C++ property from QML:
Here is my QML:
ApplicationWindow { [...] property string testString: SharedConstants.testString Component.onCompleted: {console.log("onCompleted"); console.log("testString: ", testString)}
But I will be adding other stuff to SharedConstants (e.g. enum) so I must actually register SharedConstants (as described here) in main.cpp:
// Register SharedConstants so QML can access its properties qmlRegisterType<SharedConstants>("SharedConstants", 1, 0, "SharedConstants");
Debugging shows that the designated C++ accessor function getTestString() is not invoked either.
What am I doing wrong here?qmlRegisterType registers an instantiable type, but the QML code above attempts to use it as a singleton. Either instantiate an instance of the type in QML, or use one of the singleton registration methods such as QML_SINGLETON, qmlRegisterSingletonInstance, or qmlRegisterSingletonType.