我需要在python端生成一个元组列表,并将其发送到qml并打印出来,但是当我尝试在qml端打印此列表时,它会打印:
qml: [QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject),QVariant(PyQt_PyObject)]
如何解压缩这些值?
最小示例:
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
class Plot(QObject):
def __init__(self):
QObject.__init__(self)
updCanv = pyqtSignal(list, arguments=['upd'])
@pyqtSlot()
def upd(self):
points = [(1, 2), (3, 4)]
self.updCanv.emit(points)
if __name__ == "__main__":
import sys
sys.argv += ['--style', 'material']
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
plot = Plot()
engine.rootContext().setContextProperty("plot", plot)
engine.load("main.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())
import QtQuick 2.0
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.2
ApplicationWindow {
visible: true
Button {
text: qsTr("Get points")
onClicked: plot.upd()
}
Connections {
target: plot
onUpdCanv: print(upd)
}
}
答案 0 :(得分:1)
并非所有类型都在QML中映射,例如python的类型列表被映射为QML的列表类型,但是在元组的情况下则不是,因此解决方案是使用某些等效类型或创建一些新类型,在这种情况下,由于元组有2个元素,因此您可以轻松使用QPointF()
。
class Plot(QObject):
updCanv = pyqtSignal(list, arguments=['upd'])
@pyqtSlot()
def upd(self):
points = [(1, 2), (3, 4)]
p = [QPointF(*v) for v in points]
self.updCanv.emit(p)
输出:
qml: [QPointF(1, 2),QPointF(3, 4)]