将QML信号连接到PySide2插槽

时间:2019-08-23 02:43:12

标签: python qml pyside2

我对使用Qt / C ++有一定的经验,现在我想切换到PySide2 + QML。我想将ui信号(例如单击按钮)连接到python插槽

我看到了很多示例,但是它们都不同,我想PyQt / PySide现在正在迅速改变

您能为我提供一种将QML信号连接到PySide插槽的现代且简洁的方法吗?例如,单击按钮以在python控制台中打印一些文本。这是我简单的代码示例

main.py

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

def test_slot(string): # pseudo slot
    print(string)

if __name__ == "__main__":
    app = QGuiApplication()
    engine = QQmlApplicationEngine('main.qml')
    exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13

ApplicationWindow {
    visible: true

    Button {
        anchors.centerIn: parent
        text: "Example"
        onClicked: test_slot("Test") //pseudo signal
    }
}

1 个答案:

答案 0 :(得分:1)

在这些情况下,最佳实践是创建一个QObject,将其导出到QML并在那里进行连接,就像在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")
    }
}

注意:所有C ++ / QML良好实践也都适用于Python / QML,且变化和限制很小。