nam
nam

Reputation: 3632

Error while implementing a StringListModel from QAbstractListModel in Pyqt

The purpose of this code is to show a list of string with a model herited from 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_()

The error I've got is

TypeError: rowCount() takes exactly 1 positional argument (2 given)

Upvotes: 0

Views: 936

Answers (1)

ChrisB
ChrisB

Reputation: 4718

The problem is that QAbstractItemModel.rowCount takes a 'parent' parameter. The following tweak suppresses the error (though I don't know if it actually implements the correct logic)

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

Also, are you sure that QListWidget doesn't provide the functionality you need?

Upvotes: 1

Related Questions