I found a very nice solution for using ENUMs from C++ class in QML, here:
Enums in Qt QML - qml.guide. The post was so good, I felt obliged to share it here with the SO community. And IMHO attribution should always be done, hence added the link to the post.
The post basically describes:
1) How to create an ENUM type in Qt/C++:
// statusclass.h
#include <QObject>
class StatusClass
{
Q_GADGET
public:
explicit StatusClass();
enum Value {
Null,
Ready,
Loading,
Error
};
Q_ENUM(Value)
};
2) How to register the class with QML engine as an "Uncreatable Type":
(This is the part which makes this solution nice and distinct.)
// main.cpp
...
QQmlApplicationEngine engine;
qmlRegisterUncreatableType<StatusClass>("qml.guide", 1, 0, "StatusClass",
"Not creatable as it is an enum type.");
...
Use of qmlRegisterUncreatableType
prevents instantiation of StatusClass
in QML. A warning will be logged if a user tries to instantiate this class:
qrc:/main.qml:16 Not creatable as it is an enum type.
3) Finally, how to use the ENUM in a QML file:
// main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import qml.guide 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log(StatusClass.Ready); // <--- Here's how to use the ENUM.
}
}
Important note:
ENUM is supposed to be used by referencing it with the class name, like this StatusClass.Ready
. If the same class is also being used in QML as a context property...
// main.cpp
...
QQmlApplicationEngine engine;
qmlRegisterUncreatableType<StatusClass>("qml.guide", 1, 0, "StatusClass",
"Not creatable as it is an enum type.");
StatusClass statusClassObj; // Named such (perhaps poorly) for the sake of clarity in the example.
engine.rootContext()->setContextProperty("statusClassObj", &statusClassObj); // <--- like this
...
...then, sometimes people accidentally use the ENUM with the context property instead of the class name.
// main.qml
...
Component.onCompleted: {
// Correct
console.log(StatusClass.Ready); // 1
// Wrong
console.log(statusClassObj.Ready); // undefined
}
...
The reason people tend to make this mistake is because Qt Creator's autocomplete feature lists ENUM as option, both when referencing using class name as well as the context property. So just exercise caution when in such a situation.