QAbstractItemModel - basic example
-
Hey
I somehow forgot how to build the basic abstract model...
What am I missing here? It does not display anything.
I'd like to display the 2 arrays of data as 1 long list of items... mhmhmmm
from PySide2.QtCore import QAbstractItemModel, QModelIndex print("Hello") import sys from PySide2.QtWidgets import * class model(QAbstractItemModel): def __init__(self): super(model, self).__init__() self.geoData = [] self.matData = [] self.rootItem = "imRooot" def setDataContainers(self, geo, mat): self.geoData = geo self.matData = mat def index(self, row, column, parent=None, *args, **kwargs): if self.hasIndex(row, column, parent) == False: return QModelIndex() item = 0; geoLen = len(self.geoData) if (row < geoLen): item = self.geoData[row] else: item = self.matData[row - geoLen] return self.createIndex(row, column, item) def parent(self, item): # index if item.isValid() == False: return QModelIndex() print("Eh", item) return QModelIndex() def rowCount(self, parent=None, *args, **kwargs): if (parent.isValid() == False): return len(self.geoData) + len(self.matData) return 0 def columnCount(self, parent=None, *args, **kwargs): return 3 def data(self, parent=None, *args, **kwargs): print("data?") return "hi" if __name__ == '__main__': # Create the Qt Application app = QApplication(sys.argv) w = QWidget() lay = QGridLayout() w.setLayout(lay) w.show() itemList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 10 items otherItemList = ["vdsvsd", "32tgers", "bgfnd", "egerd35yue", "esvgh53fd"] model = model() model.setDataContainers(itemList, otherItemList) v = QTreeView() v.setModel(model) lay.addWidget(v) w.setMinimumSize(500, 500) # Run the main Qt loop sys.exit(app.exec_())
-
You are trying to overload the Data function by data(parent) but the real signature of this function is data(index,role)
Try to replace for this sneap of code:
def data(self, index, role, *args, **kwargs): if role == Qt.DisplayRole: return "hi" return None
You also need to import Qt from QtCore module.
#from PyQt5.QtCore import QAbstractItemModel, QModelIndex from PySide2.QtCore import QAbstractItemModel, QModelIndex, Qt
-
@Dariusz
I think that because yourparent()
always returns an invalidQModelIndex
that could be a problem?In your
rowCount()
, the default value forparent
isNone
, which will then make your first lineif (parent.isValid() ...)
crash.I'd start from those two. Check what your
rowCount()
is returning, if it's 0 nothing is going to be shown! -
You are trying to overload the Data function by data(parent) but the real signature of this function is data(index,role)
Try to replace for this sneap of code:
def data(self, index, role, *args, **kwargs): if role == Qt.DisplayRole: return "hi" return None
You also need to import Qt from QtCore module.
#from PyQt5.QtCore import QAbstractItemModel, QModelIndex from PySide2.QtCore import QAbstractItemModel, QModelIndex, Qt