[PyKDE] PyQt4: setPaletteBackgroundColor

Gerard Vermeulen gerard.vermeulen at grenoble.cnrs.fr
Wed Feb 8 06:32:48 GMT 2006


On Tue, 7 Feb 2006 14:11:46 -0900
Patrick Stinson <patrickkidd at gmail.com> wrote:

> I relaize that this is a question for qt-interest, but I'm getting a slow
> response.
> 
> What is the preferred method for setting the background color of a widget in
> qt4? I'm using palette().setColor(QPalette.Window, mycolor)), but this
> setting for child widgets seems to be overriden by the color you set the
> parent widget with. Are you supposed to draw a rect in paintEvent()? The
> QWidget docs don't seem to say much.
> 

It is the C++ reference returned by Qt's palette() which bites you. You
change the palette, but it is still shared with the other widgets in the
widget tree that your widget is part of.

A work-around is to explicitly create a palette (from a not yet released
PyQwt-5 example):

    def __colorTheme(self, base):
        background = base.dark(150)
        foreground = base.dark(200)

        mid = base.dark(110)
        dark = base.dark(170)
        light = base.light(170)
        text = foreground.light(800)

        palette = QtGui.QPalette()
        for colorGroup in colorGroupList:
            palette.setColor(colorGroup, QtGui.QPalette.Base, base)
            palette.setColor(colorGroup, QtGui.QPalette.Background, background)
            palette.setColor(colorGroup, QtGui.QPalette.Mid, mid)
            palette.setColor(colorGroup, QtGui.QPalette.Light, light)
            palette.setColor(colorGroup, QtGui.QPalette.Dark, dark)
            palette.setColor(colorGroup, QtGui.QPalette.Text, text)
            palette.setColor(colorGroup, QtGui.QPalette.Foreground, foreground)

        return palette

    # __colorTheme()

and elsewhere __colorTheme() is used as:

    def __init__(self, *args):
        QtGui.QFrame.__init__(self, *args)
        self.setPalette(
            self.__colorTheme(QtGui.QColor(QtCore.Qt.darkGray).dark(150)))

This is a nasty pitfall, because the references returned by Qt are quite often
shared and Python programmers have to be aware of this.

Gerard




More information about the PyQt mailing list