无法从 QML 中检索 PySide Signal 参数
问题描述
我注意到 QML 可以使用 Connections 对象接收 Python 发出的信号.不幸的是,我不知道如何让该对象接收该信号的参数.
I've noticed that QML can receive a signal emitted from Python by using the Connections object. Unfortunately, I can't figure out how to get that object to receive the arguments of that signal.
我创建了一个最小的测试用例来演示我想要做什么:
I've created a minimal test case that demonstrates what I want to do:
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_()
还有 min.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?
}
}
}
}
解决方案
从 Qt 4.8 开始,PySide 根本不处理信号参数名称.
As of Qt 4.8, PySide doesn't handle signal parameter names at all.
但是您可以使用命名参数创建一个 QML 信号并使用 Javascript 将您的 python 信号连接到它:
But you can create a QML signal with named parameters and connect your python signal to it using Javascript:
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;
}
}
}
相关文章