Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. [solved] Accessing C++ constants from within QML

[solved] Accessing C++ constants from within QML

Scheduled Pinned Locked Moved General and Desktop
2 Posts 1 Posters 1.3k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    digorydoo
    wrote on last edited by
    #1

    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
    {
    private:
    Q_OBJECT
    Q_PROPERTY (QColor contentBg READ getContentBg CONSTANT)
    public:
    Colors();
    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!

    1 Reply Last reply
    0
    • D Offline
      D Offline
      digorydoo
      wrote on last edited by
      #2

      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.

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved