Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read property from QML singleton with C++

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.

like image 647
Tobias Sch. Avatar asked Aug 17 '15 15:08

Tobias Sch.


1 Answers

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
like image 100
Benp44 Avatar answered Nov 17 '22 16:11

Benp44