Is it possible to change the colour of a QTableWid

2019-03-01 15:24发布

问题:

I have a class that inherits from QTableWidget and I'm wondering if it's possible to change the colour of the row label for each row in the table?

I don't want to change the colour of any of the cells or column headings.

Thanks :)

P.S. I would like each row label to have a different colour. The motivation is that I can use these colours as a key/legend as each row in the table corresponds to a differently coloured line on a plot.

EDIT: Image illustrating the elements of the table I am referring to:

回答1:

Yes it is possible but only with a slight trick. With setVerticalHeaderItem of QTableWidget you can set a QTableWidgetItem even for header rows and there you can define a background brush for each row. However most of the times the background will be ignored because the actual QStyle will override it. Setting the style of the vertical header widget to a style that doesn't change the background however does the trick.

Example:

from PySide import QtGui

app = QtGui.QApplication([])

table = QtGui.QTableWidget(4, 2)
table.show()

for i in range(0, 4):
    item = QtGui.QTableWidgetItem('Text')
    item.setBackground(QtGui.QColor(i*50, i*30, 200-i*40))
    table.setVerticalHeaderItem(i, item)

# print(QtGui.QStyleFactory.keys())
table.verticalHeader().setStyle(QtGui.QStyleFactory.create('CleanLooks'))

app.exec_()



回答2:

Yes it appears that you can do so, using the QTableWidgetItem functions such as setForeground which you pass through a QBrush object that I believe you can use the QBrush's setColor function to pass it a color. The QTableWidgetItem documentation has a lot of aesthetic-based functions so it looks like what you're looking for especially since it seems to be able to target specific cells/items on the table. If you want to look more into the QTableWidget documentation itself, here's a link to that as well.