How to set QWidget background color?

69,788

Solution 1

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)

Solution 2

you can also use setStyleSheet for example:

w.setAttribute(Qt.Qt.WA_StyledBackground, True)
w.setStyleSheet('background-color: red;')
Share:
69,788
Johan Råde
Author by

Johan Råde

I did a Ph.D. in mathematics at University of Texas and a postdoc at Stanford University. I am one of the founders of Qlucore, a leading bioinformatics software company. I have 15 years experience of scientific computing in C++ and Python.

Updated on April 29, 2021

Comments

  • Johan Råde
    Johan Råde about 3 years

    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_()