使用自定义数据方法的自定义QStandardItemModel [英] Custom QStandardItemModel with custom data method
问题描述
我想做的是,我想制作一个带有可检查项目的listView.我可以使用QStandardItemModel作为模型来做到这一点.现在,我需要做的是添加一些需要自定义数据方法的功能.因此,就像我们要做的那样,我将QStandardItemModel子类化为一个类,并将其指定为listView的模型.现在我面临的问题是,listView仅显示文本,没有检查选项.
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_()
这是我正在尝试的一段代码.我在网上搜索了所有示例,该示例显示了如何自定义QStandardItemModel,但没有得到.
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.
推荐答案
您正在覆盖QStandardItemModel
的data
方法,但没有实现旧的data
方法处理的每个角色.您可以为所有角色实现if/elif
语句,也可以为我首选的解决方案,将那些不想自己处理的语句交给原始方法.
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.
因此,我将您的data
方法更改为:
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.
这篇关于使用自定义数据方法的自定义QStandardItemModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!