如何为QTableWidget的QStyledItemDelegate设置选中高亮色且保留默认样式
你需要在调用style.drawControl绘制单元格之前,修改QStyleOptionViewItem实例的palette属性,直接修改其中的Highlight色值即可,不需要改动全局QPalette或者自定义QStyle,也不需要手动fillRect覆盖背景,默认的选中边框、样式效果都会保留,也能解决你现在看到的选中色偏浅的问题。
具体修改步骤:
- 在
self.initStyleOption(options, index)执行完成后,判断当前单元格是否处于选中状态 - 如果是选中状态,直接修改
options.palette中Active组的Highlight颜色为你需要的数值 - 你原有代码中缺失了
text_rect的定义,需要补上这行代码,否则运行会报错
修改后的完整代码如下:
class CustomDelegate(QtWidgets.QStyledItemDelegate): def __init__(self, *args, **kwargs): super(CustomDelegate, self).__init__(*args, **kwargs) self.doc = QtGui.QTextDocument(self) self.text_edit = None def paint(self, painter, option, index): painter.save() options = QtWidgets.QStyleOptionViewItem(option) self.initStyleOption(options, index) self.doc.setPlainText(options.text) # 重置option的text,后续用QTextDocument绘制文本 options.text = "" style = QtWidgets.QApplication.style() if options.widget is None \ else options.widget.style() # ----------------- 新增修改高亮色代码 ----------------- if options.state & QtWidgets.QStyle.State_Selected: # 这里改成你需要的高亮色,比如深绿色#2e7d32,也可以直接用QtGui.QColor("green") highlight_color = QtGui.QColor("#2e7d32") options.palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Highlight, highlight_color) # 如果需要适配非激活窗口的选中色,可以加下面这行 options.palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight, highlight_color) # ------------------------------------------------------- style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter) # ----------------- 补上缺失的text_rect定义 ----------------- text_rect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options, options.widget) # ----------------------------------------------------------- # 设置文本颜色 paint_context = QtGui.QAbstractTextDocumentLayout.PaintContext() if option.state & QtWidgets.QStyle.State_Selected: paint_context.palette.setColor(QtGui.QPalette.Text, option.palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText)) else: paint_context.palette.setColor(QtGui.QPalette.Text, option.palette.color(QtGui.QPalette.Active, QtGui.QPalette.Text)) option.palette.setColor(QtGui.QPalette.Background, QtCore.Qt.black) painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) self.doc.documentLayout().draw(painter, paint_context) painter.restore()
原理说明:drawControl绘制单元格样式时会直接读取传入的options参数里的palette配置,我们只修改当前这个options实例的调色板,不会影响其他控件的样式,同时默认的选中虚线框、样式边角效果都会完整保留,不需要手动重绘任何基础样式。
内容的提问来源于stack exchange,提问作者Adam Sirrelle
相关产品推荐
相关产品推荐

