SetContextProperty multiple files
-
Hello,
I have a ReferenceError in my qml file : ReferenceError: userInterface is not defined. The error is in this line:
userInterface.backlightChanged(backlightslider.value)
but the qml link is working properly. below my code
main.cpp
QGuiApplication app(argc,argv); QQmlEngine engine; QQmlComponent component(&engine,QUrl("qrc:/QML/Qml/newMain.qml")); QObject *object = component.create(); if (component.isError()) { qDebug() << component.errors(); } UserInterface userInterface(*object); engine.rootContext()->setContextProperty("userInterface",&userInterface); return app.exec();
newMain.qml
ApplicationWindow { id: mainWindow width: 1024 height: 768 visible: true SettingsMenu{ id: settingsMenu; objectName: "SettingsMenu"} ...some more code
settingsMenu
Window { id: settingsMenu width: 1024 height: 768 color: "#d1d3d4" visible: false Slider { property bool stateVisible: false id: backlightslider x: 885 y: 525 width: 50 height: 227 onValueChanged: { userInterface.backlightChanged(backlightslider.value) }
userinterface.cpp
UserInterface::UserInterface(QObject &windowInstance) :m_object(&windowInstance) { QQuickWindow *item = qobject_cast<QQuickWindow*>(m_object); m_playButton = (item->findChild<QObject *>("PlayButton")); } void UserInterface::backlightChanged(const int &backlightLevel) { QFile backlight("/sys/class/backlight/backlight_lvds.29/brightness"); backlight.open(QIODevice::WriteOnly | QIODevice::Truncate); QTextStream out(&backlight); out << backlightLevel; backlight.close(); }
When i change the backlight slider, the signal is emitted, and received. but i still get the warning when starting the application :
ReferenceError: userInterface is not defined
What am i doing wrong?
-
Hi @neovius and Welcome,
When i change the backlight slider, the signal is emitted, and received. but i still get the warning when starting the application :
That is because you are creating QML component before setting the context property and thus naturally it wont be able to access that method at very first time.
http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html#exposing-properties
http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html#exposing-methods-including-qt-slots