I'm trying to change the color of the background of an QTableWidgetItem. There is some others posts about the same thing but none of the given solutions worked for me.
For each row, I create the QTableWidgetItems one by one and I then assign it to cells of current row with setItem.
I tried to change the color just after they have been created with :
self.myTable.myItem1.setBackgroundColor(QtGui.QColor(255,100,0,255))self.myTable.myItem1.setBackground(QtGui.QColor(255,100,0,255))self.myTable.myItem1.setData(Qt.BackgroundRole,QtGui.QColor(255,100,0,255))But these solutions do nothing in my case. Is there something I am missing ?
Any help is welcome
You have to set the background color of the item. There are a few ways to do this (full script is further down):
In this example, we are setting item1 to have "row1" as the content. If this is an even row, we then set the background to a light red/pink.
item1 = QtGui.QTableWidgetItem('row1')
if row % 2 == 0:
item1.setBackground(QtGui.QColor(255, 128, 128))
self.table.setItem(row,0,item1)
In this example, we are setting the background to a light grey on the item are Row 1, Column 0:
self.table.item(1,0).setBackground(QtGui.QColor(125,125,125))
A full script, showing both the red and the grey highlighting is here:
from PyQt4 import QtCore
from PyQt4 import QtGui
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self,parent)
self.table = QtGui.QTableWidget()
self.table.setColumnCount(2)
self.setCentralWidget(self.table)
data1 = ['row1','row2','row3','row4']
data2 = ['1','2.0','3.00000001','3.9999999']
self.table.setRowCount(4)
for row in range(4):
item1 = QtGui.QTableWidgetItem(data1[row])
if row % 2 == 0:
item1.setBackground(QtGui.QColor(255, 128, 128))
self.table.setItem(row,0,item1)
self.table.item(1,0).setBackground(QtGui.QColor(125,125,125))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With