从Pyqt中的QAbstractListModel实现StringListModel时出错

时间:2012-07-30 10:38:04

标签: python model-view-controller pyqt4

此代码的目的是显示一个字符串列表,其中包含一个来自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个)

1 个答案:

答案 0 :(得分:1)

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

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

另外,你确定QListWidget没有提供你需要的功能吗?