Custom QStandardItemModel with custom data method

pyqt, pyqt4, python, qstandarditemmodel

Solution

You are overriding the `data` method of `QStandardItemModel` but not implementing every role that the old `data` method handled. You can either implement `if/elif` statements for all roles, or my preferred solution, hand off those you don't want to deal with yourself to the original method.

Thus I would change your `data` method to read:

def data(self , index , role):
    if role == Qt.ToolTipRole:
        return self.d

    if role == Qt.DisplayRole:
        return self.d.text()

    return QStandardItemModel.data(self, index, role)

Checkboxes now show up when I make this change to your example.

Problem

what i am trying to do is , i want to make a listView with checkable items. I was able to do it using QStandardItemModel as my model. Now what i need to do is add some features that require a custom data method . So as we would do, i sub-classed QStandardItemModel into a class and appointed it as the model, for the listView. Now the problem that i face is that , the listView is only showing text and no check option. ``` from PyQt4.QtCore import * from PyQt4.QtGui import * import sys from random import randint class rrap(QStandardItemModel): def __init__(self ,parent = None): QStandardItemModel.__init__(self,parent) self.d = QStandardItem(QString("asd")) self.d.setCheckable(True) self.d.setFlags(Qt.ItemIsUserCheckable| Qt.ItemIsEnabled) self.appendRow(self.d) def data(self , index , role): if role == Qt.ToolTipRole: return self.d if role == Qt.DisplayRole: return self.d.text() app = QApplication(sys.argv) view = QListView() model = rrap() view.setModel(model) view.show() app.exec_() ``` This the piece of code that i'm trying out .I searched the net, to find any example showing how to customize a QStandardItemModel , didn't get one.

Original source