我注意到QML可以使用Connections对象接收从Python发出的信号。不幸的是,我不知道如何让该对象接收该信号的参数。
我创建了一个最小的测试用例来演示我想做什么:
min.py
from PySide import QtCore, QtGui, QtDeclarative
import sys
# init Qt
app = QtGui.QApplication(sys.argv)
# set up the signal
class Signaller(QtCore.QObject):
emitted = QtCore.Signal(str)
signaller = Signaller()
# Load the QML
qt_view = QtDeclarative.QDeclarativeView()
context = qt_view.rootContext()
context.setContextProperty('signaller', signaller)
qt_view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
qt_view.setSource('min.qml')
qt_view.show()
# launch the signal
signaller.emitted.emit("Please display THIS text!")
# Run!
app.exec_()
和最小 qml
import QtQuick 1.0
Rectangle {
width:300; height:100
Text {
id: display
text: "No signal yet detected!"
Connections {
target: signaller
onEmitted: {
display.text = "???" //how to get the argument?
}
}
}
}
从 Python 的 Qt 版本 5.12.5、5.13.1 开始,它的工作方式与 PyQt 相同:
from PySide2.QtCore import Signal
sumResult = Signal(int, arguments=['sum'])
sumResult.emit(42)
QML:
onSumResult: console.log(sum)
从Qt 4.8开始,PySide根本不处理信号参数名称。
但是你可以创建一个带有命名参数的QML信号,并使用Javascript将你的python信号连接到它:
import QtQuick 1.0
Rectangle {
width:300; height:100
Text {
id: display
text: "No signal yet detected!"
signal reemitted(string text)
Component.onCompleted: signaller.emitted.connect(reemitted)
onReemitted: {
display.text = text;
}
}
}
我无法发表评论,因为我需要更高的声誉。响应"无法分配给不存在的属性",这是由初始化应用程序的顺序引起的。需要在引擎之前创建根上下文对象。
还行:
context = Context()
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("context", context)
不行:
engine = QQmlApplicationEngine()
context = Context()
engine.rootContext().setContextProperty("context", context)