Connect QML signal to PySide2 slot

亡梦爱人 提交于 2019-12-02 07:19:23

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!