QTableWidgetItem Background Color Change

I am trying to change the background color QTableWidgetItem. There are a few more posts about the same, but none of these solutions worked for me.

For each row, I create QTableWidgetItemsone by one, and then assign it to the cells of the current row using setItem.

I tried to change the color right after it was 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 decisions do nothing in my case. Is something missing?

Any help is appreciated.

+4
source share
1 answer

You must set the background color of the element. There are several ways to do this (full script further):

  • Option 1: set the background in the element, then add the element to the table.

item1 "row1" . , /.

item1 = QtGui.QTableWidgetItem('row1')
if row % 2 == 0:
    item1.setBackground(QtGui.QColor(255, 128, 128))
self.table.setItem(row,0,item1)
  • 2: . , .

- : 1, 0:

self.table.item(1,0).setBackground(QtGui.QColor(125,125,125))

script, , :

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_())

:

Example output showing two methods of highlighting background

+4

Source: https://habr.com/ru/post/1589206/


All Articles