How to change QPushButton backround color without using CSS

Question:

So far I am only able to customize the button text color:

button = QtGui.QPushButton()
palette = QtGui.QPalette(button.palette())
palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('blue'))
button.setPalette(palette)

But how to change the button background color?

None of this will change the button background color:

    palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Button, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Light, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Midlight, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Dark, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Mid, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Text, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.BrightText, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Base, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Background, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Midlight, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Shadow, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor('red'))
    palette.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('red'))
Asked By: alphanumeric

||

Answers:

you need to set the right “role” and append “setAutoFillBackground()”:

button = QtGui.QPushButton()
palette = self.button.palette()
role = self.button.backgroundRole() #choose whatever you like
palette.setColor(role, QColor('red'))
button.setPalette(palette)
self.button.setAutoFillBackground(True)
Answered By: Thomas

Some QStyles, specifically Windows Vista, takes certain aspects of the gui from the operating system, so you can’t change them directly with a QPalette.

You can query available QStyles with

QStyleFactory.keys()

['windowsvista', 'Windows', 'Fusion']

Change the qstyle to some other Style, with

app.setStyle("Fusion")

Now, it will respect a QPalette’s

QPalette.Button
Answered By: macevhicz
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.