Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass enum class to QML?

Tags:

c++

enums

qt

qml

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

}
like image 800
Shtol Krakov Avatar asked May 24 '16 13:05

Shtol Krakov


1 Answers

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

class Helper {
   ...
};
Q_DECLARE_METATYPE(Helper::Requester)
Q_DECLARE_METATYPE(Helper::JANSWER)
like image 67
Shtol Krakov Avatar answered Sep 23 '22 11:09

Shtol Krakov