0

I am trying to get a custom ListModel to work and to be displayed in PyQt. However the list view always ends up blank. I checked that UserModel.users does have the items in it it should have, and dataChanged fires properly, however nothing shows up. At the same time, print(index) in data never outputs anything, so the model data never gets called? What am I missing?

    self.userList = QtWidgets.QListView()
    self.userList.setModel(self.main.commandHandler.userList)
    self.userList.show()

class UserModel(QAbstractListModel):
    def __init__(self, parent=None):
        QAbstractListModel.__init__(self, parent) 
        self.users = []

    def rowCount(self, parent = None) :
        if parent != None:
            return 0
        return len(self.users)

    def flags(self):
        return Qt.NoItemFlags

    def data(self, index, role = Qt.DisplayRole ):
        print(index)
        name = self.users[index].name
        if index.isValid():
            if (role == Qt.DisplayRole):
                return QVariant(name)
        else:
            return QVariant()

    def addUser(self, payload):
        user = User(payload)
        l = len(self.users)
        self.users.append(user)
        self.dataChanged.emit(self.index(l, 0), self.index(l, 0))
Whitecold
  • 281
  • 1
  • 3
  • 8

1 Answers1

0

You'll need to call beginInsertRows and endInsertRows - dataChanged is only for existing items.

You might want to run pytest-qt's modeltester over your model to find more issues.

Also, note there's QStandardItemModel and QStringListModel which might be easier to use if your actual model is as simple as your example.

The Compiler
  • 11,126
  • 4
  • 40
  • 54
  • I tried adding beginInsertRows and endInsertRows, it does not change anything. As for trying out pytestqt, something seems off with the tester as well. It returns an error in hasIndex, which I do not overwrite, and should not have to. – Whitecold May 05 '17 at 17:21
  • Could you open [an issue](https://github.com/pytest-dev/pytest-qt/issues) with the model and the exact error you get? – The Compiler May 05 '17 at 18:33