Is it possible to access/read the properties of a QML singleton inside your C++ code?
For example if my QML singleton looks like this:
pragma Singleton
import QtQuick 2.5
QtObject {
property int myProperty: 5
}
How can I access myProperty from C++ code. I need this as I do not want to have my "magic" numbers both in QML and C++ and it is only very rarely required in C++.
For normal QQuickItem's it was always easy. Just get access to the QuickItem (by dynamic creating it or with findChild()) and than call quickItem->property("myProperty").toInt()
But with the singleton I can't see how to get access to it.
Although not directly, one way to access a QML singleton is via a function in a non-singleton QML object, that you can access in the usual way:
Constants.qml
pragma Singleton
import QtQuick 2.5
QtObject {
objectName: "Constants"
property double phi: 1.6180339887498948482
}
main.qml (e.g.)
import QtQuick 2.5
import "."
function getPhi()
{
return Constants.phi;
}
C++
//...
// Create the engine and load QML
//...
QObject* rootObject = engine->rootObjects().constFirst();
QVariant phi;
QMetaObject::invokeMethod(rootObject, "getPhi", Q_RETURN_ARG(QVariant, phi));
qDebug() << phi.toFloat();
Don't forget you'll need a qmldir file to access the singleton in QML:
qmldir
singleton Constants Constants.qml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With