How to emit Signal from nested QML page (by Loader) to python
-
Dear, in my QML/python app I can emit signal from main.qml to the python code. But now In main.qml I added StackLayout for loading another page1.qml. In that page1.qml is button, now I want to emit signal from this button to the python.
I use this simple method for emit signals from main.qml file to the python: But I do not know how to emit it from "nested" page1.qml to the python. What should I modify? This code works when emits from main.qml
from PySide2.QtCore import QObject, QUrl, Slot, Signal, Qt from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine class Foo(QObject): @Slot(str) def test_slot(self, input_string : str): print(input_string) if __name__ == "__main__": import os import sys app = QGuiApplication() foo = Foo() engine = QQmlApplicationEngine() #CHANGES: line excluded engine.rootContext().setContextProperty("foo", foo) qml_file = "main.qml" current_dir = os.path.dirname(os.path.realpath(__file__)) filename = os.path.join(current_dir, qml_file) engine.load(QUrl.fromLocalFile(filename)) if not engine.rootObjects(): sys.exit(-1) #CHANGES: connect QML signal to Python slot engine.rootObjects()[0].test_signal.connect(foo.test_slot, type=Qt.ConnectionType.QueuedConnection) sys.exit(app.exec_())
main.qml
import QtQuick 2.13 import QtQuick.Controls 2.13 ApplicationWindow { visible: true //CHANGES: declare signal signal test_signal(string input_string) Button { anchors.centerIn: parent text: "Example" //CHANGES: emit signal onClicked: test_signal("Test string") } }
-
I guess if you create a function in your main qml in which this signal is sent out. And call this func from page1. This will work. Other people may have better ideas. If you have signals at different layers, you may want to create a global model and call the model to emit these signals.
-
You don't.
C++ shouldn't connect to QML signals.
Expose a slot/invokable function in a Python object that is accessible from QML and call that slot in QML.