How to pass enum class to QML?

2019-04-30 01:11发布

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:
            }
        }
    }

}

标签: c++ qt enums qml
1条回答
Lonely孤独者°
2楼-- · 2019-04-30 01:41

The problem was in Helper class (thanks to Qt community).

class Helper {
   ...
};
Q_DECLARE_METATYPE(Helper::Requester)
Q_DECLARE_METATYPE(Helper::JANSWER)
查看更多
登录 后发表回答