无法从 QML 检索 PySide 信号参数

Tha*_*all 6 python pyside qml pyside2

我注意到 QML 可以使用 Connections 对象接收从 Python 发出的信号。不幸的是,我无法弄清楚如何让该对象接收该信号的参数。

我创建了一个最小的测试用例来演示我想要做什么:

最小.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_()
Run Code Online (Sandbox Code Playgroud)

和 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?
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*sdm 6

从 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;        
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*gen 6

对于 Python 版本 5.12.5、5.13.1 的 Qt,它的工作方式与 PyQt 相同:

from PySide2.QtCore import Signal

sumResult = Signal(int, arguments=['sum'])
sumResult.emit(42)
Run Code Online (Sandbox Code Playgroud)

QML:

onSumResult: console.log(sum)
Run Code Online (Sandbox Code Playgroud)