How to pass enum class to QML?
-
Hello everyone!
I am on learning to QML with Qt and get some trouble with passing enum class to qml.
When I use signal with int parameters - it's all right and code work perfectly.
But, and here the trouble, if I use signal with some enum class parameters I have undefined values in qml signal handler. I tried to register enum class through qmlRegisterType but it's not working. I will be grateful for the help.
Here the code:
Some Helper class
class Helper : public QObject { Q_OBJECT Q_ENUMS(Requester) Q_ENUMS(JANSWER) public: enum class Requester { ReqLogin, ReqNull, ReqSave, ReqError, ReqUnknown }; enum class JANSWER { OK, Complete, Error, Unknown }; };
main.cpp
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<JsonPackWorker>("com.jsonpackworker", 1, 0, "JsonPackWorker"); qmlRegisterType<Helper>("com.Helper", 1, 0, "Helper"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
JsonPackWorker.h
class JsonPackWorker : public QObject { Q_OBJECT public: <...> signals: <...> void sendAnswer(Helper::Requester req, Helper::JANSWER answer); public slots: <...> };
Somewehere in JsonPackWorker.cpp
emit sendAnswer(Helper::Requester::ReqNull, Helper::JANSWER::OK);
main.qml
<...> import com.jsonpackworker 1.0 import com.Helper 1.0 ApplicationWindow { id: mainWindow // Requests in answers property int reqLogin: Helper.ReqLogin <...> JsonPackWorker { id: packWorker <...> onSendAnswer: { // Here I've got undefined undefined if there enum class parameters console.log(req + " " + answer) switch(req) { case reqLogin: loginDial.checkLogin(answer) break; default: } } } }
-
Hi @someoneinthebox and Welcome,
Apart from the rest you also need to declare both the enums as
Q_DECLARE_METATYPE
.
So insideHelper
:class Helper { ... }; Q_DECLARE_METATYPE(Helper::Requester) Q_DECLARE_METATYPE(Helper::JANSWER)
-
@someoneinthebox You're Welcome :)
Btw. if you are using Qt 5.5 or greater then use Q_ENUM instead as Q_ENUMS are deprecated.