How to provide data from PySide QAbstractItemModel subclass to QML ListView?

懵懂的女人 提交于 2019-12-23 16:53:53

问题


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

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

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

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 } }
}

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?


回答1:


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



来源:https://stackoverflow.com/questions/4013615/how-to-provide-data-from-pyside-qabstractitemmodel-subclass-to-qml-listview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!