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:
The same code under Linux does not lose the other button stylings and produces:
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
2
Answers
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: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:allows the background to be correctly set using the code in the question.
This Qt/C++ answer shows the way
Basically, something like:
In all my PyQt coding I find I’m unable to alter any stylesheet settings. Doing so means I will no longer be able to conform to the desktop style. Note that the style can change dynamically, such as when the user switches to night mode or swaps from a dark to light theme (which adds more complexities, such as responding by changing custom button and icon backgrounds).