I am trying to change the background color for certain header sections. Some will use the default coloring, others will get a different color.
The HeaderView doesn’t accept delegates like the QTreeView does; it does all the painting itself. It does this using two methods —
My initial attempt was to try and override paintSection, letting it paint the default stuff, and then adding my own.
def paintSection(self, painter, rect, logicalindex):
QHeaderView.paintSection(self, painter, rect, logicalindex)
painter.save()
painter.fillRect(rect, QBrush(Qt.red))
painter.restore()
This doesn’t appear to do anything. It will not draw the filled rect. If I comment out the call to the base paintSection method, it will draw the filled rect, but not very consistently (i.e. clicking and resizing the header causes it to fill sometimes and not others).
Any help is appreciated.
There is no need to implement anything
QHeaderViewcan be changed through stylesheets like almost all widgets.Edit:
You mentioned that you wanted to change the background color per column depending on data, the easiest way to do that is probably to derive a new model from
QAbstractItemModelor another model class and reimplement theheaderData()callthe role that you want to react to is
Qt::BackgroundColorRoleso the function could look like thisGenerally in Qt, the model decides what to show, almost all of the times change the model, not the view. Also the ‘data()’ calls get called a lot, I don’t know about the ‘headerData()’ but you probably want to cache any results if there is a lot of calculation going on.
If you are using the
QStandardItemModelyou can probably just call