【发布时间】:2016-04-13 12:48:21
【问题描述】:
这似乎与此处的问题相同(未答复):QML Combobox reports ReferenceError: modelData is not defined。我能找到的 QT 数据库中最接近(已关闭)的错误是:https://bugreports.qt.io/browse/QTBUG-31135 所以我不确定这是同一个问题。我正在运行 PyQt5 v5.5 和 python 3.4.3。
我正在 PyQt5 中实现一个 QAbstractListModel,并将代码提炼到手头的问题:
# ExampleModel.py
class ExampleModel(QAbstractListModel):
def __init__(self, parent=None):
super().__init__(parent)
self.items = []
for t in range(0,10):
self.items.append({'text': t, 'myother': 'EXAMPLE'})
def data(self, index, role):
key = self.roleNames()[role]
return self.items[index.row()][key.decode('utf-8')]
def rowCount(self, parent=None):
return len(self.items)
def roleNames(self):
return {Qt.UserRole + 1: b'text',
Qt.UserRole + 2: b'myother'}
以及相关的 QML:
# example.qml
...
ComboBox { // Displays blank entires + throws ReferenceError
id: comboExample
model: ExampleModel{}
textRole: 'text' # This was the missing line to make this work.
}
ListView { // Works Correctly
id: listExample
model: ExampleModel{}
delegate: Text {
text: myname + " " + myother
}
}
...
当我运行这个时,组合框有 10 个空白条目,并且控制台错误日志显示:
[path]/ComboBox.qml:562: ReferenceError: modelData is not defined
(x 10)
现在,如果我将上面 ExampleModel.py 中的 roleNames() 代码修改为以下内容:
def roleNames(self):
return {Qt.UserRole + 1: b'myname'}
ComboBox 工作正常。
我在这里遗漏了一个关键概念吗?我不想实现我的模型两次(一次用于此 ComboBox 解决方法。)
编辑
通过在上面的 example.qml 中添加 Mitch 的建议,这个问题得到了解决。 代码已相应更新。
【问题讨论】:
标签: python qt qml qtquick2 pyqt5