Custom QStandardItemModel with custom data method

女生的网名这么多〃 提交于 2019-12-22 11:23:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21518935/custom-qstandarditemmodel-with-custom-data-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!