在Pyside中使用定义模型的QListView

4 投票
1 回答
3215 浏览
提问于 2025-04-17 13:10

我一直在尝试用PySide显示一个我自己构建的列表。这个列表并不是简单的字符串列表(要是简单的话我可以用QListWidget),不过为了举例我把它简化了。

from PySide import QtCore, QtGui

class SimpleList(QtCore.QAbstractListModel):
    def __init__(self, contents):
        super(SimpleList, self).__init__()
        self.contents = contents

    def rowCount(self, parent):
        return len(self.contents)

    def data(self, index, role):
        return str(self.contents[index.row()])


app = QtGui.QApplication([])
contents = SimpleList(["A", "B", "C"]) # In real code, these are complex objects
simplelist = QtGui.QListView(None)
simplelist.setGeometry(QtCore.QRect(0, 10, 791, 391))
simplelist.setModel(contents)
simplelist.show()
app.exec_()

我看到的只是一个空列表,什么都没有

我哪里做错了呢?

1 个回答

3

你应该检查一下 role 这个参数:

def data(self, index, role):
    if role == QtCore.Qt.DisplayRole:
        return str(self.contents[index.row()])

不过很奇怪,QTableView 可以和任何 role 一起使用。

撰写回答