因此,PySide2删除了QVariant *类型。
但是,QtQuick公开了大量QVariant API。
更具体地说,我想使用非常方便的功能将QVariantList传递为ListView的模型,而无需实现完全成熟的QAIM。
但是,通过setContextProperty将此类对象提供给QML
class Test(QObject):
def __init__(self):
super(Test, self).__init__()
self.propertyList = ["FOO", "BAR", 1]
def model(self):
return self.propertyList
modelChanged = Signal()
model = Property(list, model, notify=modelChanged)
然后打印.model产生:
qml: QVariant(PySide::PyObjectWrapper)
那么如何以qml真正理解的形式将python列表传递给qml?
答案 0 :(得分:1)
您必须将属性类型传递给"QVariantList"
:
from PySide2 import QtCore, QtGui, QtQml
class Test(QtCore.QObject):
modelChanged = QtCore.Signal()
def __init__(self, parent=None):
super(Test, self).__init__(parent)
self.propertyList = ["FOO", "BAR", 1]
def model(self):
return self.propertyList
model = QtCore.Property("QVariantList", fget=model, notify=modelChanged)
if __name__ == "__main__":
import sys
app = QtGui.QGuiApplication(sys.argv)
pyobject = Test()
engine = QtQml.QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("pyobject", pyobject)
engine.load(QtCore.QUrl.fromLocalFile("main.qml"))
engine.quit.connect(app.quit)
sys.exit(app.exec_())
import QtQuick 2.12
import QtQuick.Window 2.12
Window{
visible: true
width: 640
height: 480
Component.onCompleted: console.log(pyobject.model)
}
输出:
qml: [FOO,BAR,1]
注意:如果将python的PyQt5列表直接转换为QML列表,则与PySide2不同,您必须指出Qt的类型,如果它们不直接作为类型存在,则必须将其表示为串。