Issue
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?
Solution
You can do this by using the following recipe:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MyFrame(QtWidgets.QFrame):
def __init__(self, parent=None,initials=None):
QtWidgets.QFrame.__init__(self, parent)
self.table = QtWidgets.QTableWidget(5,3,self)
self.table.move(30,30)
self.table.resize(400,300)
item1 = QtWidgets.QTableWidgetItem('red')
item1.setBackground(QtGui.QColor(255, 0, 0))
self.table.setHorizontalHeaderItem(0,item1)
item2 = QtWidgets.QTableWidgetItem('green')
item2.setBackground(QtGui.QColor(0, 255, 0))
self.table.setHorizontalHeaderItem(1,item2)
item3 = QtWidgets.QTableWidgetItem('blue')
item3.setBackground(QtGui.QColor(0, 0, 255))
self.table.setHorizontalHeaderItem(2,item3)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setStyle(QtWidgets.QStyleFactory.create('Fusion')) # won't work on windows style.
Frame = MyFrame(None)
Frame.resize(500,400)
Frame.show()
app.exec_()
, that will result in this:
One thing you must consider is that Windows style does not let you do this. This is the reason why I had to change the style to Fusion.
Answered By - armatita
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.