How to color a PyQt QTabwidget

JohnSantaFe picture JohnSantaFe · Nov 6, 2013 · Viewed 9.7k times · Source

I have a PyQt main window that contains a QTabWidget. The tab widget contains a few buttons and text boxes.

I'd like to color the entire tab background not just the tabs that stick up in the tab bar area.

I'm not using style sheets and would prefer to use a palette since I'm already using palettes, but if style sheets are the only option, that's ok.

I've tried:

p = self.tabWidget.palette()
p.setColor(self.tabWidget.backgroundRole(), Qt.red)
self.tabWidget.setPalette(p)

This produces a red tab bar area, but the main background is still white.

Turning off autofill, with self.tabWidget.setAutoFillBackground(False) makes a slight difference, the individual tabs are now nicely colored but the main body is still white.

Trying a little style sheet:

self.tabWidget.setStyleSheet("QWidget {background-color: yellow }")

This colors the main body of the tab, however it also colors everything else yellow including the buttons and text boxes. Also, all the little tabs that stick up are all yellow. Autofill did not have any affect.

Any ideas on how to color the body of the tab but not wipe out the other widgets?

I'm using PyQt version 4.10 and Python 2.7.

Answer

Using StyleSheet, you could do something like this:

stylesheet = """ 
    QTabBar::tab:selected {background: gray;}
    QTabWidget>QWidget>QWidget{background: gray;}
    """

self.setStyleSheet(stylesheet)

The chevrons allows to refer to the child of a widget. It tells Qt to apply the stylesheet on the grand-children of any QTabWidget in your application (see Qt StlyleSheet syntax). The tab "body" are grand-children of the QTabWidget.

It doesn't render very nicely as it is, you will have to adjust some setting. See Qt documentation on Customizing QTabWidget and QTabBar.