My Firmware

My Firmware

Embedded development

© 2020

Sharing enums between QML and C++

Recently I stumbled upon the need to use common enum in both C++ and QML to allow for typesafe control of the C++ backend. After some Googling I found out this solution:

namespace EnumNamespace {
    Q_NAMESPACE
    enum MyEnum {
        ValueOne,
        ValueTwo
    };

    Q_ENUM_NS(MyEnum)
}
Q_DECLARE_METATYPE(EnumNamespace::MyEnum)

In main.cpp:

qmlRegisterUncreatableMetaObject(
            EnumNamespace::staticMetaObject,
            "Import.Statement",
            1, 0,
            "EnumNamespace",
            "Error: Cannot create EnumNamespace"
    );
qRegisterMetaType<EnumNamespace::MyEnum>();

Now we are able to use the enum in QML like this: print(EnumNamespace.ValueOne). For use in QML called C++ methods the methods needs to be implemented like: Q_INVOKABLE void useEnum(EnumNamespace::MyEnum enum).

WARNING: without the use of Q_DECLARE_METATYPE and qRegisterMetaType calling method with the enum arguments doesn’t work, failing with Error: Unknown method parameter type: EnumNamespace::MyEnum.