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.



  • Whoops, this should probably be in the QML sub-forum, if so, could a moderator please move it? Sorry about that.



  • You have to register your class:
    qmlRegisterType<MyCustomQMLClass>("MyComponents", 1, 0, "MyCustomQMLClass");
    and in QML:
    import MyComponents 1.0

    MyComponents.SomeEnumMember ...


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.