[solved] Accessing C++ constants from within QML

  • I'm having trouble accessing C++ constants from within QML. I'm trying to create a Q_OBJECT that holds Q_PROPERTYs:

    class Colors: public QObject
    Q_PROPERTY (QColor contentBg READ getContentBg CONSTANT)
    virtual ~Colors() { }
    QColor getContentBg() const { return QColor ("#fefa07"); }

    Then I register the type through qmlRegisterUncreatableType:

    int main(int argc, char *argv[])
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    qmlRegisterUncreatableType<Colors> ("FirstQtTest.Defs", 1, 0, "Colors", "Instances of Colors are disallowed!");
    engine.load (QUrl (QStringLiteral ("qrc:///main.qml")));
    return app.exec();

    My QML file then tries to access the colour constant like this:

    import FirstQtTest.Defs 1.0
    // ...
    color: Colors.contentBg;

    I keep getting the runtime error: "Unable to assign [undefined] to QColor". What am I doing wrong?

    Thanks in advance!

  • I managed to get it to work by replacing qmlRegisterUncreatableType with setContextProperty:

    Colors colors;
    engine.rootContext()->setContextProperty ("Colors", &colors);

    I still can't tell why qmlRegisterUncreatableType doesn't work, but the above works fine in my case.

Log in to reply

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