我对使用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 } }
在这些情况下,最佳实践是创建一个QObject,将其导出到QML并在那里进行连接,这也是在C ++中完成的。
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_())
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,且更改和限制最少。