[PyKDE] PyQt4: setPaletteBackgroundColor

V. Armando Sole sole at esrf.fr
Thu Feb 9 07:26:55 GMT 2006


Hi Gerard,

At 20:08 08/02/2006 +0100, Gerard Vermeulen wrote:
>Please, read my mail again.  You are trying to do something which you
>cannot do without a cast in C++, because QWidget::palette() returns
>'const QPalette&'.  Python does not know about constness, and therefore
>PyQt hands you a rope to hang yourself.
>
>The road to independent palettes reads:
>
>     palette = QPalette()
>     setColorRoles(palette)
>     self.setPalette(palette)
>     palette = QPalette()
>     setOtherColorRoles(palette)
>     self.parentWidget().setPalette(palette)

As pointed out by "David Boddie" <david at boddie.org.uk> :

[begin quote]

You can make the child widget visible by adding the following
line:

         self.w.setAutoFillBackground(True)

Contents propagation is enabled by default in Qt 4.1.0. For custom
widgets where you reimplement QWidget's paintEvent(), you can do
various things to allow effects like partial transparency for child
widgets while still adding your own colour scheme. However, a plain
QWidget has to draw itself, so this seems like the quickest way to
get what you want.

David
[end quote]

The missing  call setAutoFillBackground(True) was the critical thing.

The code below works as intended.


from PyQt4.QtCore import *
from PyQt4.QtGui import *

class AllGreen(QWidget):
     def __init__(self):
         QWidget.__init__(self)
         layout = QVBoxLayout(self)

         self.w1 = QWidget(self)
         self.w1.setFixedSize(100, 100)
         self.w2 = QWidget(self)
         self.w2.setFixedSize(100, 100)
         self.w3 = QWidget(self)
         self.w3.setFixedSize(100, 100)

         palette = self.palette()
         role = self.backgroundRole()
         palette.setColor(role, QColor('green'))
         self.setPalette(palette)

         palette = self.w1.palette()
         role = self.w1.backgroundRole()
         palette.setColor(role, QColor('red'))
         self.w1.setPalette(palette)

         palette = self.w2.palette()
         role = self.w2.backgroundRole()
         palette.setColor(role, QColor('yellow'))
         self.w2.setPalette(palette)

         palette = self.w3.palette()
         role = self.w3.backgroundRole()
         palette.setColor(role, QColor('red'))
         self.w3.setPalette(palette)

         layout.addWidget(self.w1)
         layout.addWidget(self.w2)
         layout.addWidget(self.w3)

def testWidget():
     import sys
     a = QApplication(sys.argv)
     QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))

     w = AllGreen()
     w.w1.setAutoFillBackground(True)
     w.w2.setAutoFillBackground(True)
     w.w3.setAutoFillBackground(True)
     w.show()

     a.exec_()

if __name__ == "__main__":
     testWidget()


Regards,

Armando 




More information about the PyQt mailing list