QML and C++ Signal Interface w/ Dynamically Loaded QML Objects
-
So I have an application in which I am using QML to provide the UI and visual elements and C++ to provide some more complex back-end functionality of the app. I am trying to figure out how to interface the two.
Following this guide:
http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.htmlAn example is using QML signals to trigger a C++ slot. This works nicely if you have a simply static root hierarchical QML object structure - like their simple example where a you simply do a root object lookup of a QML view for the file that was loaded.
However, in my case, while using a loader or similar to dynamically load a QML page at runtime, how would I reference signals from those "deeper" dynamic sub-objects in C++?
Here is a simple example of my use case to help clarify the issue:
// main.cpp QQuickView view(QUrl(QLatin1String("qrc:/main_page.qml"))); // How can we access signals or objects in the // "some_other_page.qml" loaded instance? // main_page.qml Item { Loader { id: myLoader source: "some_other_page.qml" active: true } }
-
Ok I figured out a way to do this in the case of a Loader, looking at our page with the loader we can reference the "sub signal" and connect it a signal in the local page. This upper level signal can then be connected to the slot in C++ code.
// main_page.qml signal qmlSignal(string msg) Item { Loader { id: myLoader source: "some_other_page.qml" active: true onLoaded: { item.anotherqmlSignal.connect(qmlSignal) } } }
Another way to make a connection but maybe more crude is to use a "Connection" type and then call the sub-signal from the handler.
Not sure if this is the best way but this seems to work.