PySide6 QAbstractTableModel:将布尔值替换为居中对齐图标
解决QAbstractTableModel中布尔值图标居中的问题
你的核心问题是找错了控制装饰元素(图标)对齐的属性——displayAlignment和textAlignment是控制文本对齐的,而DecorationRole对应的图标对齐需要用option.decorationAlignment来设置。
修正后的IconDelegate代码
直接在initStyleOption方法里添加装饰对齐的设置即可:
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QStyledItemDelegate class IconDelegate(QStyledItemDelegate): def initStyleOption(self, option, index): super().initStyleOption(option, index) option.decorationSize = QSize(16, 16) # 设置图标在单元格内居中对齐 option.decorationAlignment = Qt.AlignCenter
给表格绑定Delegate
需要把这个Delegate应用到对应的布尔列上,比如:
# 假设你的表格是tableView,布尔列索引为0 tableView.setItemDelegateForColumn(0, IconDelegate())
如果有多个布尔列,可以遍历所有列,判断列类型后批量设置。
关于角色的说明
你之前对角色的理解是对的:
DecorationRole专门用于返回图标、装饰类元素,模型里的代码逻辑没问题;DisplayRole仅用于返回文本内容,确实无法显示图标,所以不用考虑切换到这个角色。
内容的提问来源于stack exchange,提问作者Byte Insight
相关产品推荐
相关产品推荐

