[PyKDE] QTable cell color - better way ?

Dave S eric3 at pusspaws.net
Sun Sep 3 09:41:38 BST 2006


As a relative newbe to GUI & QT programming I am trying to get various 
background colours for a QTable call. Extensive googling & headscratching has 
come up with re-defining paint() for each color. This seems like a lot of 
code & I wondered if there is a more elegant way ? A kind of 
self.table1.setColor(row, col, color) would be nice - or is this the only 
way :)

Dave



class TableItemRed(QTableItem):
    """ Red background table item"""
    def __init__(self, table, edittype, text):
        QTableItem.__init__(self, table, edittype, text)

    def paint(self, painter, colorgroup, rect, selected):
        cg = QColorGroup(colorgroup)
        cg.setColor(QColorGroup.Base, Qt.red)  # Base = background color of 
text widgets
        QTableItem.paint(self,painter, cg, rect, selected)  # Qt.colors in 
Qcolor

class TableItemYellow(QTableItem):
    """ Yellow background table item """
    def __init__(self, table, edittype, text):
        QTableItem.__init__(self, table, edittype, text)

    def paint(self, painter, colorgroup, rect, selected):
        cg = QColorGroup(colorgroup)
        cg.setColor(QColorGroup.Base, Qt.yellow)  # Base = background color of 
text widgets
        QTableItem.paint(self,painter, cg, rect, selected)  # Qt.colors in 
Qcolor

######################################################
        
        self.tableitemred = TableItemRed(self.table1,QTableItem.Never,"")
        self.tableitemyellow = 
TableItemYellow(self.table1,QTableItem.Never,"") 
        self.tableitemgreen = TableItemGreen(self.table1,QTableItem.Never,"") 
        self.tableitemgray = TableItemGray(self.table1,QTableItem.Never,"")  
        self.tableitemdefault = QTableItem(self.table1,QTableItem.Never,"")  


######################################################

        if color == 'red': self.table1.setItem(row, col, self.tableitemred)    
        elif color == 'yellow': self.table1.setItem(row, col, 
self.tableitemyellow) 
        elif color == 'green': self.table1.setItem(row, col, 
self.tableitemgreen) 
        elif color == 'gray': self.table1.setItem(row, col, 
self.tableitemgray) 
        
        self.table1.setText(row, col, text)
        self.table1.updateCell(row, col)  # Update the cell to re-paint its 
contents 




More information about the PyQt mailing list