How to connect multiple QML files to backend PySide2

Viewed 187

I am builder an application with Python and QML using QtQuick with PySide2. I have multiple QML files in my application that need to communicate with the backend. I currently have only my main QML file connected.

Inside my main QML file I have the connection set up:

Connections{
    target: con
}

Python code:

class MainWindow(QObject):

    def __init__(self):
        QObject.__init__(self)
    .
    .
    .

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    main = MainWindow()
    engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))
    engine.rootContext().setContextProperty("con", main)

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

What would I do in the main function in order to setup multiple QML files that would communicate with the backend?

1 Answers

The objects exposed using setContextProperty() are global, that is, they can be accessed in all .qml so you must do the same as you do in main.qml.

On the other hand it is recommended that you use setContextProperty() before load():

main = MainWindow()
engine.rootContext().setContextProperty("con", main)

engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))
Related