C++ Enums in QML with setContextProperty
-
So I am trying to utilize enums from C++ in a custom class which I have registered an instance of in QML via the setContextProperty method.
i.e.
MyCustomQMLClass myclass; view.engine()->rootContext()->setContextProperty("myQmlClassInstance", &myclass)
I have enums declared within this class, which I have registered with qml via the Q_ENUM macro.
i.e.class MyCustomQMLClass: Public QObject { Q_OBJECT public: enum SomeEnum {SomeEnumMember, SecondEnumMember}; Q_ENUM(SomeEnum) .....
The problem is, I can't seem to be able to use them however. Most of the examples seem to be using the
qmlRegisterType method of C++/QML integration which registers a generic type which is then instantiated in QML (which would be of MyCustomQMLClass in the example above).https://doc.qt.io/qt-5/qtqml-cppintegration-data.html#enumeration-types
When looking at the examples, the enums are referenced then via the custom QML type name, not the instance itself (i.e. Message.Ready).
Since I am using the set context property method where I am registering an instance of a class and not the generic type, I do not know what the type name would be in order to reference the enum. myQmlClassInstance.SomeEnumMember does not work (seems to be undefined) and neither does SomeEnumMember (QML has an error saying it can't find that reference).
Not sure what the proper way to register them is in this case. Hope this makes sense.
-
You have to register your class:
qmlRegisterType<MyCustomQMLClass>("MyComponents", 1, 0, "MyCustomQMLClass");
and in QML:
import MyComponents 1.0MyComponents.SomeEnumMember ...
-
Register it as a singleton type instead of using setContextProperty:
MyCustomQMLClass myclass; qmlRegisterSingletonType<MyCustomQMLClass>("org.orgname.app", 1, 0, "myQmlClassSingleton", [&](QQmlEngine *, QJSEngine *) -> QObject * { return &myclass; // return new MyCustomQmlClass is also valid because the QML engine takes ownership of the singleton });
Then use it in QML like this:
import org.orgname.app 1.0 ... Component.onCompleted { console.log(myQmlClassSingleton.SomeEnumMember); }
For more info: https://zditect.com/code/cpp/qtqml-expose-c-classes-to-qml-and-why-setcontextproperty-is-a-not-the-best-idea.html
-
@kengineer said in C++ Enums in QML with setContextProperty:
MyCustomQMLClass myclass;
view.engine()->rootContext()->setContextProperty("myQmlClassInstance", &myclass)you can use context as well. But it is better to define it with pointer.
auto myclass = new MyCustomQMLClass;
view.engine()->rootContext()->setContextProperty("myQmlClassInstance", myclass);
if not with a pointer, myclass is gone if it is set in a func.
You also need to clear it when it is not needed.