QQmlContext::setContextProperty: property is not defined.



  • Hi;

    // main.cpp
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    
    int main(int argc, char* argv[])
    {
      QGuiApplication app(argc, argv);
    
      QQmlApplicationEngine engine;
      engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
      QQmlContext* context = new QQmlContext(engine.rootContext());
      context->setContextProperty("num", 77);
    
      return app.exec();
    }
    
    // MainForm.ui.qml
    import QtQuick 2.5
    
    Rectangle {
      width: 360
      height: 360
      property alias text0: text0.text
      Text {
        id: text0
        x: parent.width / 2
        y: parent.height / 2
      }
    }
    // main.qml
    import QtQuick 2.5
    import QtQuick.Window 2.2
    
    Window {
      visible: true
    
      MainForm {
        anchors.fill: parent
        text0: num
      }
    }
    

    This code is getting this error message: qrc:/main.qml:9: ReferenceError: num is not defined but I defined num property in main.cpp. What is the problem? Thanks.



  • The problem is that you don't provide the property to the root context but to a copy...
    you should rather use this :

    QQmlContext* context = engine.rootContext();
    context->setContextProperty("num", 77);
    //engine.rootContext()->setContextProperty("num", 77); //even simpler
    


  • @Charby Thanks. The problem solved.



  • Context properties must be set before loading QML that references the context properties.


Log in to reply
 

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