Search code examples
pythonpyqt5

Change background colour of PyQt5 QPushButton without losing the default button style


I have a basic code for a PyQt5 GUI with two buttons. In it, I want to change the the background colour of one of the buttons. I do this by setting the background-color style sheet attribute for the button. This works, however, under Windows it seems to remove all other style attributes for the button, leaving an unattractive button compared to the standard one, as shown in the image:

GUI in Windows

The same code under Linux does not lose the other button stylings and produces:

enter image description here

where things like the default button rounded corners and hover attributes are kept.

The code is:

import sys

from PyQt5.QtWidgets import QApplication, QGridLayout, QPushButton, QWidget

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.layout = QGridLayout()

        button1 = QPushButton("A")
        button1.setFixedSize(64, 64)
        button2 = QPushButton("B")
        button2.setFixedSize(64, 64)

        button2.setStyleSheet("background-color: #ff0000")

        self.layout.addWidget(button1, 0, 0)
        self.layout.addWidget(button2, 0, 1)

        self.setLayout(self.layout)
        self.show()


app = QApplication([])

demo = Window()
demo.show()

sys.exit(app.exec())

Is is possible to set the background without losing the other attributes under Windows (11)?

On Windows, I'm running in a conda environment with:

pyqt                      5.12.3
pyqt5-sip                 4.19.18
pyqtchart                 5.12
pyqtwebengine             5.12.1
qt                        5.12.9

and on Linux (Ubuntu 20.04.5 running via WSL2) I'm running in a conda environment with:

pyqt                      5.15.7
pyqt5-sip                 12.11.0
qt-main                   5.15.2
qt-webengine              5.15.9
qtconsole                 5.3.2

Solution

  • Based on the comments, it seems that if you want to change the style sheet for a QPushButton on Windows you need to also specify all the other style attributes that you want as well. From the documentation here, if shows an example of this (when changing the background colour using a style sheet) and states:

    • We have made a request that cannot be satisfied using the native styles alone (e.g., the Windows Vista theme engine doesn’t let us specify the background color of a button).

    • Therefore, the button is rendered using style sheets.

    • We haven’t specified any values for border-width and border-style , so by default we obtain a 0-pixel wide border of style none.

    where the first bullet is particularly relevant.

    Update

    One thing that has worked, is to explicitly set the overall app's style, so that it doesn't use the "Windows" style. E.g, having:

    app = QApplication([])
    app.setStyle("Fusion")
    

    allows the background to be correctly set using the code in the question.