QQmlContext::setContextProperty: property is not defined.
Solved
QML and Qt Quick
-
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
-
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.