Share enum between C++ and QML / header file



  • Hello all,

    I am aware about the following technique to share enum among C++ and QML:

    @class MyClass : public QDeclarativeView
    {

        Q_OBJECT
        Q_ENUMS(Tasks)
     
    public:
        enum Tasks { Task1, Task2, Task3 };
    }
    

    In c++ file:
    qmlRegisterType<MyClass>(...)
    @

    I would like to do exactly the same but with my enum definition being in an external .h file like:
    @myFile.h
    enum Tasks { Task1, Task2, Task3 };

    now what should I do to get my enum recognized in my class?
    #include "myFile.h"

    class MyClass : public QDeclarativeView
    {

        Q_OBJECT
        Q_ENUMS(Tasks)
     
    public:
       --
    }
    

    In c++ file:
    qmlRegisterType<MyClass>(...)

    This compiles alright, but the enum values are undefined when using them in the QML part
    @

    Any solution for this?
    Thank you!

    Bill



  • The only thing I can think of, is to pull dirty tricks on moc. Qt itself does this: it pretends that it is dealing with QObjects on the moc run, but not in the compile run. Q_ENUMS only works in the context of a QObject...



  • found an ugly workaround too:
    declared a QObject class in my enum header file like this:
    @
    myFile.h
    class MyEnum: public QObject
    {
    Q_OBJECT
    Q_ENUMS(someEnum)

    pubilc:
    enum someEnum {A, B, C}
    }
    typedef MyEnum::someEnum t_someEnum;

    In some C++ file that requires this enum type
    cppFile.h
    #include myFile.h
    class SomeClass
    {
    public:
    t_someEnum mEnum;
    }
    when defining a method requiring one of the value use
    mEnum = MyEnum::A;

    In the C++ files that will register the qml enum, simply include the myFile in the header file MyClass.h, in the constructor register the enum for qml with qmlRegisterType<..>("...",1,0,"QMLENUM")
    Now use the enum values A, B, C directly in QML by calling QMLENUM.A for instance.
    @


Log in to reply
 

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