Using same constants in QML Scripts and C++
-
Hello,
I have started a QML application and I would like to use same constants in QML scripts AND in C++ part.
I will have 50 to 100 constants (most of them will be some strings) to define.
What are possibilities to do it ?Thanks.
-
@FabQ hi
this is 6 years old but still can help https://forum.qt.io/topic/19557/solved-exporting-functions-and-constants-from-c-to-qmlmight i ask you what to use these constants ?
-
I think, what you're looking for is the QGlobalStatic Class, To access it in QML, you should make it available via
rootContext()->setContextProperty("Name",Instance Pointer);
This this link for more information -
Please consider using the Q_ENUM tag:
class Constants : public QObject { Q_OBJECT public: enum ConstantValues{ MinValue = 0, MaxValue = 65535 }; Q_ENUM(ConstantValues) };
Now you can access
Constants::MinValue
with C++ andConstants.MinValue
with QML. -
@FabQ
To add to what @GPBeta wrote, this requires you to register theConstants
classqmlRegisterType<Constants>("your.module", 0, 1, "Constants");
http://doc.qt.io/qt-5/qtqml-cppintegration-data.html#enumeration-types
-
All solutions revolve around registering the class with QML. You can consider using Q_GADGET, if you don't want to inherit from QObject while exposing constants to QML.
6/7