微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

QStyledItemDelegate:添加禁用的检查指示器

如何解决QStyledItemDelegate:添加禁用的检查指示器

我正在使用带有自定义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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。