I am referencing code as written by eyllanesc here: https://stackoverflow.com/a/53357083/3950707
When a cell on my QTableWidget
is selected I want the default select colour displayed:
However, after setting the initStyleOption
, this lighter colour displayed:
I am not certain what I need to change in order to set a new Highlight
colour.
Is this something I need to change in option before it is passed into a QStyleOptionViewItem
, or is it something I need to change in a QPalette
or QStyle
somewhere?
I know I can used painter.fillRect()
to set a colour to the background, but this then overloads the default style, removing the grey dotted lines from around the cell.
I'm hoping that I can avoid the need to rebuild everything in paint by setting the colour for Highlight
similarly to a stylesheet
's hover, checked etc.
Below is the abridged code I am using.
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
Unfortunately, I was unable to find how to change the style of a control element, but adding the options widget into drawControl
seems to return the correct colors.
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
change to:
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter, options.widget)