[PyKDE] QTable cell color - better way ?
Jim Bublitz
jbublitz at nwinternet.com
Mon Sep 4 06:34:28 BST 2006
On Sunday 03 September 2006 01:41, Dave S wrote:
> 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 SomeKindOFTableItem (QTableItem):
def __init__ (self, table, value):
# use default colors unless explicitly set
self.bgColor = None
self.fgColor = None
# not all of these are necessary - depends on which you want
def setColor (self, bgColor, fgColor):
# bgColor, fgColor are QColor constants - eg QColor (0xff, 0x11, 0x00), or
# Qt.red
self.bgColor = bgColor
self.fgColor = fgColor
def setBGColor (self, bgColor):
self.bgColor = bgColor
def setFGColor (self, fgColor):
self.fgColor = fgColor
def paint (self, painter, colorgrp, rect, selected):
if self.fgColor:
colorgrp.setColor (QColorGroup.Text, self.fgColor)
if self.bgColor:
colorgrp.setColor (QColorGroup.Base, self.bgColor)
QTableItem.paint (self, painter, colorgrp, rect, selected)
then, for example:
self.table.item (row, col).setColor (Qt.red, Qt.blue)
(of course (row,col) must have a QTableItem set - if you don't know, you need
to test for that).
I prefer to do it in the table item, because then the table item can respond
automatically to its value, for example a negative $ amount in red, positive
in black, or a table item can hold some kind of object that knows its status
and displays a corresponding color automatically. A table item knows its row
and column too, so it can respond to those as well. (You can have paint() do
the color setting automatically instead of providing explicit "set" methods
too)
In fact, I prefer to make table items fairly smart - they can know if they're
dollar amounts, integers, strings, telephone numbers, postal codes and all
sorts of things so they can format and validate themselves. Then you can
overload QTable to "know" what table item type belongs in a particular
column, and have it create the right type automatically - not too much
harder. .
Jim
More information about the PyQt
mailing list