问题描述
我正在使用带有自定义QTreeView
的{{1}}来显示各种参数项。我希望所有项目都具有一个检查指示器,但是应禁用某些复选框(但仍可见并设置为选中状态!)。
这是代表代码:
QStyledItemDelegate
我是否必须篡改class MyDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
def initStyleOption(self,option,index):
super().initStyleOption(option,index)
option.features |= QtWidgets.QStyleOptionViewItem.HasCheckIndicator
if index.data(MyItem.ROLE_OPTIONAL):
#Disable check indicator here!
才能完成这项工作?
解决方法
假设当OP表示:某些复选框应被禁用(但仍可见并且设置为选中状态!)表示它将该项显示为已禁用,并且用户无法更改其状态复选框,则必须更改QStyleOptionViewItem的状态,另一方面,必须在editorEvent方法中返回false:
class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self,option,index):
super().initStyleOption(option,index)
if index.data(MyItem.ROLE_OPTIONAL):
option.state &= ~QtWidgets.QStyle.State_Enabled
def editorEvent(self,event,model,index):
if index.data(MyItem.ROLE_OPTIONAL):
return False
return super().editorEvent(event,index)
,
如果eyllanesc提供的solution不是OP所需要的,我假设所需要的是该项目仍然具有一个选中的复选框,并且仍处于启用/可编辑状态,但该项目未设置QtCore.Qt.ItemIsUserCheckable
标志。
在这种情况下,解决方案是将要使用的模型子类化,并为QtCore.Qt.Checked
角色返回QtCore.Qt.CheckStateRole
。
class SomeModel(InheritedModelClass):
def data(self,index,role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.CheckStateRole and self.data(index,ROLE_OPTIONAL):
return QtCore.Qt.Checked
return super().data(index,role)
如果已经使用了模型子类,这也将起作用,因为如果覆盖了子类,则足以将第一个if role ==
条件添加到当前存在的data()
实现中。
如果出于任何原因 do 项设置了ItemIsUserCheckable标志,则flags()
函数也必须被覆盖:
def flags(self,index):
# get the flags from the default implementation
flags = super().flags(index)
if self.data(index,ROLE_OPTIONAL):
# remove the checkable flag
flags &= ~QtCore.Qt.ItemIsUserCheckable
return flags