我使用带有自定义QStyledItemDelegate的QTreeView来显示各种参数项。我希望所有的项目都有一个检查指示器,但是一些复选框应该被禁用(但仍然可见并设置为选中!)。
以下是委派代码:
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!我必须篡改MyDelegate.paint()才能使其工作吗?
发布于 2020-09-09 23:41:54
假设操作员说:应该禁用某些复选框(但仍然可见并设置为选中!)指示它将该项显示为已禁用,并且用户无法更改checkbox的状态,则您必须更改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, option, index):
if index.data(MyItem.ROLE_OPTIONAL):
return False
return super().editorEvent(event, model, option, index)发布于 2020-09-10 02:38:12
如果eyllanesc提供的solution不是OP正在寻找的,我假设需要的是该项目仍然有一个选中的复选框,并且仍然是启用/可编辑的,但是该项目没有设置QtCore.Qt.ItemIsUserCheckable标志。
在这种情况下,解决方案是对将要使用的模型进行子类化,并为QtCore.Qt.CheckStateRole角色返回QtCore.Qt.Checked。
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()实现添加第一个条件就足够了。
如果出于任何原因,这些项确实设置了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 flagshttps://stackoverflow.com/questions/63811651
复制相似问题