3
votes

I'm having trouble getting the actual background color of widgets. In my special case I'm having trouble with widgets within a QTabWidget.

This is on Windows7. So classic widgets have some greyish background, whereas widgets within a tab are generally drawn with a white background.

I tried:

def bgcolor(widget):
    color = widget.palette().color(widget.backgroundRole()) # version 1
    color = widget.palette().color(QtGui.QPalette.Background) # version 2
    rgba = color.red(), color.green(), color.blue(), color.alpha()
    return rgba

which is pretty much what I could figure out myself from the Qt documentation and what google and SO give. But, this just doesn't work.

I'm testing widgets inside and outside of a TabWidget and the function above returns identical colors for obviously differently colored widgets. Namely it always returns the greyish color, even for the plain white colored widgets within the tab.

Am I missing something here?

EDIT:

My problem is when using matplotlib, matplotlib draws figures with a "none" facecolor with the wrong background color when embedded in a QTabWidget: grey, even though the parent widget is white.

To fix this I wanted to get the background color of the widget and set it as background color for the figure. Though this may be a matplotlib issue, I guessed this would be the quickest workaround. As I noticed I couldn't get the proper color, I became insistent :)

1

1 Answers

4
votes

The palette is returning the correct colours.

The mistake you're probably making is that you're assuming "background" always means the same thing for all widgets. Let's take an unmodified QListWidget as an example. On a desktop with a traditional light-coloured scheme, this will probably appear as a white viewport inside a 3D sunken panel. But if you query the "background" for this widget, you will see something like this:

>>> widget = QtGui.QListWidget()
>>> widget.palette().color(QtGui.QPalette.Background).name()
'#edecec'

which is obviously not white. So Background is the wrong color role to query for this widget. Instead, it looks like Base might be more appropriate:

>>> widget.palette().color(QtGui.QPalette.Base).name()
'#ffffff'

It's worth noting that the documentation for color roles states that Background and Foreground are obsolete values, with Window and WindowText being recommended instead. Perhaps this is because the former terms are now considered to be misleading.

UPDATE:

On platforms which use pixmap-based styling, some of the reported palette colours will not match the visual appearance of a widget. This issue specifically affects Windows and OSX, and so may explain why you are not able to get the apparent background colour of tabs. This issue is documented in a Qt FAQ, which also gives some possible solutions (although the QProxyStyle option is supported in PyQt5 but not PyQt4).