Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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.



  • I copied the (non-working) code from a Qt 5.12.3 help page.
    I am not sure why they put it in examples if that code doesn't work. :(
    @Charby your code works seamlessly. Thanks a ton for clarifying this to all of us!


  • Lifetime Qt Champion

    Hi @zeFreelance and welcome to devnet,

    What example would that be ?



  • @SGaist said in QQmlContext::setContextProperty: property is not defined.:

    What example would that be ?

    I have seen this bad code and copy and pasted it myself without realizing I was creating a new context object. It was on stackoverflow if I remember right. I don't think I have seen this as an example on Qt docs pages though.


Log in to reply