【发布时间】:2011-04-30 03:24:04
【问题描述】:
我正在使用 PySide 编写一个具有 QML UI 的应用程序。我在 Python 中对 QAbstractListModel 进行了子类化:
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:
model = MyModel()
view.rootContext().setContextProperty("mymodel", model)
Qt's docs say 模型的角色名称用于访问来自 QML 的数据,并且可以将 QML 中的普通 DisplayRole 称为“显示”,因此我的 QML 有一个带有简单委托的 ListView,如下所示:
ListView {
anchors.fill: parent
model: mymodel
delegate: Component { Text { text: display } }
}
但是,当我这样做时,结果是file:///foo/bar/main.qml:28: ReferenceError: Can't find variable: display。
在模型中设置自定义角色名称没有帮助。想法?
【问题讨论】:
-
QML 似乎没有正确使用我的模型,因为在我向 rowCount() 添加了一些日志记录之后,我注意到它没有被调用:/ 那可能是根本原因。我仍然不知道为什么。
-
我从 rowCount() 中删除了父索引有效性检查,这实际上似乎修复了动态添加项目 (beginInserRows(...) ... endInsertRows())。我没有在这里展示那一点,因为我觉得它无关紧要。
-
我也一直在努力让它工作!我一直在关注doc.qt.nokia.com/4.7/qdeclarativemodels.html 示例,我还没有找到一个 pyside 等价物。您是否尝试过设置委托 Text { text: modelData } 请参阅:qt.gitorious.org/pyside/pyside-examples/commit/…
-
是的,这只会导致 python 出现段错误,至少在我的 Ubuntu Maverick 机器上:p
-
我已经设法让它在不使用 QAbstractListModel 的情况下工作,可在此处进行测试:syrris-support.com/Downloads/JMM/pyside_qml_tests.zip