此代码的目的是显示带有继承自模型的字符串列表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 个)