C++ enum in QML is undefined



  • Hi there,

    I got a problem using C++ enums in my QML code

    Here is the class definition containing the enumeration I want to expose in App.hpp

    #ifndef APP_HPP
    #define APP_HPP
    
    #include <QObject>
    
    class App : public QObject {
        Q_OBJECT
        Q_ENUMS(View)
    public:
        enum View {
            MainView,
            BrowserView,
            SettingsView
        };
    };
    
    #endif
    

    here is the main.cpp file

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include "App.hpp"
    
    int main(int argc, char *argv[]) {
        QApplication application(argc, argv);
        App app;
        QQmlApplicationEngine engine;
        engine.rootContext()->setContextProperty("App", &app);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        return application.exec();
    }
    

    and here is the actual QML code in main.qml

    import QtQuick 2.4
    import QtQuick.Window 2.2
    
    ApplicationWindow {
        title: qsTr("My App")
        visible: true
        width: 640
        height: 480
        Text {
            text: "main view: " + App.MainView
        }
    }
    

    The result is not satisfying, this is what I get, an undefined value

    After a long while trying to find a solution by myself I gave up, I still don't understand what I could have done wrong.
    Could somebody please help me out with that?


  • Lifetime Qt Champion

    Hi,

    Here you can find a nice explanation on how to do it



  • @SGaist
    I finally figured it out now, the problem was that I didn't register my class in main.cpp using the qmlRegisterType from <QtQml>. The code below works

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include <QtQml>
    #include "App.hpp"
    
    int main(int argc, char *argv[]) {
        QApplication application(argc, argv);
        App app;
        QQmlApplicationEngine engine;
        qmlRegisterType<App>("SomeLib", 1, 0, "App");
        engine.rootContext()->setContextProperty("App", &app);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        return application.exec();
    }
    

    main.qml

    import QtQuick 2.4
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.3
    import SomeLib 1.0
    
    ApplicationWindow {
        title: qsTr("My App")
        visible: true
        width: 640
        height: 480
        Text {
            text: "main view: " + App.BrowserView
        }
    }

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.