Color individual horizontal headers of QTableWidget in PyQt

Viewed 15991

I have a QTableWidget where I would like to color individual horizontal header items based on some criterion.

What I have come up with so far:

stylesheet = "::section{Background-color:rgb(190,1,1)}"
self.ui.Table.horizontalHeader().setStyleSheet(stylesheet)

This works, however it colors all headers simultaneously without me being able to change the color of an individual header. So the next logical step would be:

self.ui.Table.horizontalHeaderItem(0).setStyleSheet(stylesheet) 

This does not work, as a single header item does not support setting a stylesheet.

Finally:

self.ui.Table.horizontalHeaderItem(0).setBackgroundColor(QtCore.Qt.red)

This runs just fine without python complaining, however it does not seem to have any effect on the background color whatsoever.

I already looked at this answer, it is what sparked my first attempt. However it only deals with coloring all headers with the same color.

How can I color the headers individually?

2 Answers

setBackground seems to have no effect When used in header

See this: https://forum.qt.io/topic/74609/cannot-set-the-backgroud-color-of-the-horizontalheaderitem-of-qtablewidget/2

I wrote this small app; font type and size and foreground color take effect.

from PyQt4 import QtGui
from PyQt4.QtGui import QFont

app = QtGui.QApplication([])

columns = ['Column 0', 'Column 1', 'Column 2']
items = [['Row%s Col%s' % (row, col) for col in range(len(columns))] for row in range(1)]

view = QtGui.QTableWidget()

view.setColumnCount(len(columns))
view.setHorizontalHeaderLabels(columns)
view.setRowCount(len(items))
for row, item in enumerate(items):
    for col, column_name in enumerate(item):
        item = QtGui.QTableWidgetItem("%s" % column_name)
        view.setItem(row, col, item)
    view.setRowHeight(row, 16)

fnt = QFont()
fnt.setPointSize(15)
fnt.setBold(True)
fnt.setFamily("Arial")

item1 = view.horizontalHeaderItem(0)
item1.setForeground(QtGui.QColor(255, 0, 0))
item1.setBackground(QtGui.QColor(0, 0, 0))  # Black background! does not work!!
item1.setFont(fnt)

item2 = view.horizontalHeaderItem(1)
item2.setForeground(QtGui.QColor(0, 255, 0))
item2.setFont(fnt)

item3 = view.horizontalHeaderItem(2)
item3.setForeground(QtGui.QColor(255, 0, 255))

view.setHorizontalHeaderItem(0, item1)
view.setHorizontalHeaderItem(1, item2)
view.setHorizontalHeaderItem(2, item3)
view.show()
app.exec_()

enter image description here

Related