30

The line w.setBackgroundRole(QPalette.Base) in the code below has no effect. Why? How do I fix that?

import sys
from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication(sys.argv)
w = QWidget()
w.setBackgroundRole(QPalette.Base)
w.show()
app.exec_()
Xantium
  • 11,201
  • 10
  • 62
  • 89
Johan Råde
  • 20,480
  • 21
  • 73
  • 110

2 Answers2

69

You need to call setAutoFillBackground(True) on the widget. By default, a QWidget doesn't fill its background.

For more information, see the documentation for the setAutoFillBackground property.

If you want to use an arbitrary background color, you need to modify the widget's palette instead:

p = w.palette()
p.setColor(w.backgroundRole(), Qt.red)
w.setPalette(p)
jmk
  • 1,938
  • 14
  • 15
  • 5
    Welcome to stackoverflow! Thanks for answering both the "why" and the "how"! – Johan Råde Sep 29 '12 at 19:05
  • 4
    No problem. I should add that the Qt documentation is a bit unclear: the `QPalette::Window` role is used to fill a widget's background if it is a top-level window. Otherwise, your widget's `backgroundRole` is used instead, so your code should work as expected. – jmk Sep 29 '12 at 19:07
  • so its self.widget.setAutoFillBackground(True) – pippo1980 May 09 '22 at 17:41
8

you can also use setStyleSheet for example:

w.setAttribute(Qt.Qt.WA_StyledBackground, True)
w.setStyleSheet('background-color: red;')
Mohammad Nazari
  • 2,535
  • 1
  • 18
  • 29