C++ use constants that defined in qml singleton file
-
Hi,
I have more than 100 constants that defined in qml and that file made singleton in qml. Now that I need some of the constant to be used in C++. How to get it?
Thanks in advance
-
hi @DhanyaRaghav
One way to do that would be to create a c++ method that takes the needed values as parameters.You will need to expose that class to QML to be able to call the method
see here if you have Qt 5.7 and later https://doc.qt.io/qt-5/qtqml-cppintegration-topic.html
or this article https://scythe-studio.com/en/blog/how-to-integrate-qml-and-c-expose-object-and-register-c-class-to-qmlsee also Overview - QML and C++ Integration
-
I was able to resolve
//main.cpp
I did using this lines in main.cpp
QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/pathToThatQmlFile.qml")));
QObject *object = component.create();
C++ClassName::getInstance()->setObject(object);//C++
As this qml file is singleton, in C++ class where constants need to be called,
In constructor add:
qmlRegisterSingletonType(QUrl(QStringLiteral("qrc:/pathToQmlFile.qml")), "com.Test.TestConstants", 1, 0, "TestConstants");void C++ClassName::setObject(QObject *newObject)
{
item = qobject_cast<QQuickItem *>(newObject);
qDebug() << item->property("phi").toDouble);
}//QML
pragma Singletonimport QtQuick 2.14
Item
{
readonly property double phi: "3.142"
}