How to change Qtablewidget's specific cells background color in pyqt
Asked Answered
C

2

12

I am new in pyqt4 and I can't figure out how to do this. I have a QtableWidget with data in it. I want to change some background color of the tableWidget's cells.

I tried self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150)) and it returns this error:

AttributeError: 'NoneType' object has no attribute 'setBackground'

What should I do?

Cremate answered 19/9, 2013 at 7:50 Comment(1)
I'm not familiar with pyqt4 myself, but maybe you could add an SSCCE? That might make it easier for others to reproduce your problem.Armillary
W
36

You must first create an item in that place in the table, before you can set its background color.

self.tableWidget.setItem(3, 5, QtGui.QTableWidgetItem())
self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150))
Wheeling answered 19/9, 2013 at 21:42 Comment(1)
Works the same way in PyQt5 still.Atomics
R
0
import sys
from PyQt4 import QtGui, QtCore

lista = ['aa', 'ab', 'ac']
listb = ['ba', 'bb', 'bc']
listc = ['ca', 'cb', 'cc']
mystruct = {'A':lista, 'B':listb, 'C':listc}

class MyTable(QtGui.QTableWidget):
    def __init__(self, thestruct, *args):
        QtGui.QTableWidget.__init__(self, *args)
        self.data = thestruct
        self.setmydata()

    def setmydata(self):
        n = 0
        for key in self.data:
            m = 0
            for item in self.data[key]:
                newitem = QtGui.QTableWidgetItem(item)
                if key == 'A':
                    newitem.setBackground(QtGui.QColor(100,100,150))
                elif key == 'B':
                    newitem.setBackground(QtGui.QColor(100,150,100))
                else:
                    newitem.setBackground(QtGui.QColor(150,100,100))
                self.setItem(m, n, newitem)
                m += 1
            n += 1

def main(args):
    app = QtGui.QApplication(args)
    table = MyTable(mystruct, 5, 3)
    table.show()
    sys.exit(app.exec_())

if __name__=="__main__":
    main(sys.argv)

Slightly Modifiled version of http://www.saltycrane.com/blog/2006/10/qtablewidget-example-using-python-24/

Ranket answered 19/9, 2013 at 20:22 Comment(1)
This is a too complex example for a tiny problemKatherinakatherine

© 2022 - 2024 — McMap. All rights reserved.