如何从 PySide QAbstractItemModel 子类向 QML ListView 提供数据? [英] How to provide data from PySide QAbstractItemModel subclass to QML ListView?

查看:74
本文介绍了如何从 PySide QAbstractItemModel 子类向 QML ListView 提供数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 PySide 中编写的应用程序,它有一个 QML 用户界面.我在 Python 中对 QAbstractListModel 进行了子类化:

I have an app I'm writing in PySide that has a QML UI. I have subclassed QAbstractListModel in Python:

class MyModel(QtCore.QAbstractListModel):
    def __init__(self, parent=None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self._things = ["foo", "bar", "baz"]

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self._things)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole:
            return self._things[index.row()]
        return None

我通过在主脚本中执行此操作将模型提供给我的 QML:

I provide the model to my QML by doing this in the main script:

model = MyModel()
view.rootContext().setContextProperty("mymodel", model)

Qt 的文档说 模型的角色名称用于访问数据来自 QML,并且可以将 QML 中的普通 DisplayRole 称为显示",因此我的 QML 有一个 ListView 和一个简单的委托,如下所示:

Qt's docs say that the model's role names are used to access the data from QML, and that one can refer to the normal DisplayRole in QML as "display", therefore my QML has a ListView with a simple delegate like this:

ListView {
         anchors.fill: parent
         model: mymodel
         delegate: Component { Text { text: display } }
}

但是,当我这样做时,结果是 file:///foo/bar/main.qml:28: ReferenceError: Can't find variable: display.

However, when I do this the result is file:///foo/bar/main.qml:28: ReferenceError: Can't find variable: display.

在模型中设置自定义角色名称无济于事.想法?

Setting custom role names in the model does not help. Ideas?

推荐答案

需要为模型设置角色名称才能访问QML中的数据;

You need to set the role names for the model to be able to access the data in QML;

http://doc.qt.io/archives/qt-4.7/qabstractitemmodel.html#setRoleNames

这篇关于如何从 PySide QAbstractItemModel 子类向 QML ListView 提供数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆