Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change QTableWidgetItem Background Color

Tags:

python

qt

pyqt

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 :

  1. self.myTable.myItem1.setBackgroundColor(QtGui.QColor(255,100,0,255))
  2. self.myTable.myItem1.setBackground(QtGui.QColor(255,100,0,255))
  3. 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

like image 954
Olivier Giniaux Avatar asked May 21 '15 12:05

Olivier Giniaux


1 Answers

You have to set the background color of the item. There are a few ways to do this (full script is further down):

  • Option 1: Set the background on the item, then add the item to the table.

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)
  • Option 2: Set the background on an already existing item in the table. This requires that you operate directly on the item.

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:

Example output showing two methods of highlighting background

like image 57
Andy Avatar answered Sep 29 '22 18:09

Andy