没有为在 QAbstractListModel 中具有多个角色的 QML ComboBox 定义 modelData

modelData is not defined for QML ComboBox with more than one role in QAbstractListModel

这似乎是与此处相同(未答复)的问题: . The closest (closed) bug in the QT database I can find is: https://bugreports.qt.io/browse/QTBUG-31135 所以我不确定这是同一个问题。我正在 运行ning 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 解决方法。)

编辑

通过将 Mitch 的建议添加到上面的 example.qml,此问题已解决。 代码已相应更新。

您需要将 textRole 设置为您要显示的角色的名称("text",在您的情况下)。

文档可能对此更清楚,所以我创建了一个 bug report