Using QListView with a model defined in Pyside

I am trying to display a list that I am creating using PySide. This is not just a list of strings (or I could use a QListWidget ), but I simplified it for an example.

 from PySide import QtCore, QtGui class SimpleList(QtCore.QAbstractListModel): def __init__(self, contents): super(SimpleList, self).__init__() self.contents = contents def rowCount(self, parent): return len(self.contents) def data(self, index, role): return str(self.contents[index.row()]) app = QtGui.QApplication([]) contents = SimpleList(["A", "B", "C"]) # In real code, these are complex objects simplelist = QtGui.QListView(None) simplelist.setGeometry(QtCore.QRect(0, 10, 791, 391)) simplelist.setModel(contents) simplelist.show() app.exec_() 

I see nothing , just an empty list.

What am I doing wrong?

+4
source share
1 answer

You should check the role argument:

 def data(self, index, role): if role == QtCore.Qt.DisplayRole: return str(self.contents[index.row()]) 

But strangely, QTableView works with any role .

+3
source

Source: https://habr.com/ru/post/1397028/


All Articles