How to set QWidget background color?

Question:

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_()
Asked By: Johan Råde

||

Answers:

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)
Answered By: jmk

you can also use setStyleSheet for example:

w.setAttribute(Qt.Qt.WA_StyledBackground, True)
w.setStyleSheet('background-color: red;')
Answered By: Mohammad Nazari
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.