Connect QML signal to PySide2 slot

后端 未结 1 853
温柔的废话
温柔的废话 2021-01-16 06:42

I have some expirience using Qt/C++ and now I want to switch to PySide2 + QML. I want to connect ui signals, such as clicking a button, to python slot

I have seen ma

1条回答
  •  无人共我
    2021-01-16 07:31

    The best practice in these cases is to create a QObject, export it to QML and make the connection there as it is also done in C++.

    main.py

    from PySide2.QtCore import QObject, QUrl, Slot
    from PySide2.QtGui import QGuiApplication
    from PySide2.QtQml import QQmlApplicationEngine
    
    
    class Foo(QObject):
        @Slot(str)
        def test_slot(self, string):
            print(string)
    
    
    if __name__ == "__main__":
        import os
        import sys
    
        app = QGuiApplication()
        foo = Foo()
        engine = QQmlApplicationEngine()
        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)
        sys.exit(app.exec_())
    

    main.qml

    import QtQuick 2.13
    import QtQuick.Controls 2.13
    
    ApplicationWindow {
        visible: true
    
        Button {
            anchors.centerIn: parent
            text: "Example"
            onClicked: foo.test_slot("Test")
        }
    }
    

    Note: All C++/QML good practices also apply in Python/QML with minimal changes and restrictions.

    0 讨论(0)
提交回复
热议问题