【问题标题】:Setting the Highlight color within a QStyledItemDelegate on a QTableWidget在 QTableWidget 上的 QStyledItemDelegate 中设置突出显示颜色
【发布时间】:2021-11-22 01:22:01
【问题描述】:

我在这里引用 eyllanesc 编写的代码:https://stackoverflow.com/a/53357083/3950707

当我的QTableWidget 上的一个单元格被选中时,我希望显示默认的选择颜色:

但是,在设置initStyleOption之后,这个颜色变浅了:

我不确定我需要更改什么才能设置新的Highlight 颜色。 在将其传递给QStyleOptionViewItem 之前,这是我需要在选项中更改的东西,还是我需要在某个地方更改QPaletteQStyle 的东西?

我知道我可以使用painter.fillRect() 为背景设置颜色,但这会重载默认样式,从单元格周围删除灰色虚线。 我希望通过设置Highlight 的颜色类似于stylesheet 的悬停、选中等,我可以避免重建绘画中的所有内容。

以下是我正在使用的节略代码。

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)

        # Resets option text
        options.text = ""

        style = QtWidgets.QApplication.style() if options.widget is None \
            else options.widget.style()

        #print(option.palette.highlight())
        #print(style.standardPalette().highlight())
        #print (dir(style.standardPalette()))

        style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)

        # Set text colour
        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))
            #painter.fillRect(option.rect, QtGui.QColor("green"))

        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()

        return

【问题讨论】:

    标签: python pyside pyside2 qtablewidget qstyleditemdelegate


    【解决方案1】:

    不幸的是,我无法找到如何更改控件元素的样式,但将选项小部件添加到 drawControl 似乎可以返回正确的颜色。

    style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
    

    改为:

    style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter, options.widget)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2011-11-04
      • 1970-01-01
      • 2014-11-11
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多