如何在 PySide2 中将 python 列表转换为 QVariantList

How to convert a python list to a QVariantList in PySide2

因此,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)

那么如何将一个 python 列表以 qml 真正理解的形式传递给 qml?

您必须将类型 属性 传递给 "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]

注意: 在 PyQt5 的情况下 python 的列表直接转换为 QML 的列表,与 PySide2 不同,您必须指出 Qt 的类型,如果它们不存在则直接作为类型,您必须将其指示为字符串。