0

此代码的目的是显示带有继承自模型的字符串列表QtCore.QAbstractListModel

import sys
from PyQt4 import QtGui, QtCore

class StringListModel(QtCore.QAbstractListModel):
    def __init__(self, strings):
        QtCore.QAbstractListModel.__init__(self)
        self._string_list = strings
    def rowCount(self):
        return len(self._string_list)
    def data(self, index, role):
        if not index.isValid() : return QtCore.QVariant()
        if role != QtCore.Qt.DisplayRole : return QtCore.QVariant()
        if index.row() <= self.rowCount() : return QtCore.QVariant()
        return QtCore.QVariant(self._string_list[index.row()])
    def headerData(self, section, orientation, role = QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole : return QtCore.QVariant()
        if orientation == QtCore.Qt.Horizontal : return QtCore.QVariant("Column %s"%section)
        else:
            return QtCore.QVariant("Row %s"%section)

if __name__ == '__main__':
    a = QtGui.QApplication(sys.argv)
    lines = ["item 1", "item 2", "item 3"]
    model = StringListModel(lines)
    view = QtGui.QListView()
    view.setModel(model)
    view.setWindowTitle("String list model")
    view.show()
    a.exec_()

我得到的错误是

TypeError:rowCount() 正好采用 1 个位置参数(给定 2 个)

4

1 回答 1

1

问题是 QAbstractItemModel.rowCount 采用“父”参数。以下调整抑制了错误(虽然我不知道它是否真的实现了正确的逻辑)

def rowCount(self, parent=None):
    return len(self._string_list)

另外,您确定 QListWidget 不提供您需要的功能吗?

于 2012-07-30T13:41:24.797 回答