开发者

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

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()]
        r开发者_如何学Pythoneturn 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜