I try to set the background color of pushButton.checked()
. It works fine if the button is enabled and pushButton.checked() == False
, it sets the background color to disabled
color of styleSheet()
But if the button is disabled and the pushButton.checked() == True
it doesn't change the background color.
I've tried the workarounds in this post, without luck. Some others are close to the posts links.
The example below: Use lower button to enable(disable the upper and use the upper button to set it checked/unchecked and enable/disable it with the lower one to see what I mean. The background should always gray it the button is disabled.
Is there a special setting or combination required?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(300,300)
self.pushButton1 = QPushButton("see css result", self)
self.pushButton1.setCheckable(True)
#self.pushButton1.setAutoFillBackground (True) # mentioned in
self.pushButton1.setStyleSheet(css_pushButton())
self.pushButton1.resize (100, 40)
self.pushButton1.move(50,50)
print("scc1:", self.pushButton1.styleSheet())
self.pushButton_control = QPushButton("Button Enabled", self)
self.pushButton_control.setCheckable(False)
self.pushButton_control.clicked.connect(self.pushButton_control_clicked)
self.pushButton_control.move(50,100)
self.pushButton_control.resize (100, 40)
def pushButton_control_clicked(self):
print("Checked:",self.pushButton1.isChecked())
if self.pushButton1.isEnabled():
print("set False")
self.pushButton1.setEnabled(False)
self.pushButton_control.setText(('DISABLED'))
else:
self.pushButton1.setEnabled(True)
self.pushButton_control.setText(('ENABLED'))
print("set True")
def css_pushButton():
css = '''
QPushButton {
font-size: 10px;
background-color: green;
color: black;
border: 2px green;
border-radius: 22px;
border-style: outset;
}
QPushButton:hover {
background: qradialgradient(
cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 grey, stop: 1 lightgray
);
}
QPushButton:enabled{
color: black;
font: 10px;
background: green;
background-color: red;
border: 1px black;
border-style: outset;
}
QPushButton:pressed {
color: white;
background: yellow;
}
QPushButton:disabled {
color: gray;
background-color: gray;
border: 1px black;
border-style: outset;
}
QPushButton:checked{
color: black;
font: 12px;
font: bold;
background-color: red;
border: 1px black;
border-style: outset;
}
QPushButton:!checked{
color: black;
font: 12px;
font: bold;
background-color: green;
border: 1px black;
border-style: outset;
}
'''
return css
if __name__ == "__main__":
app = QApplication (sys.argv)
prog = MainWindow()
prog.show ()
app.exec_ ()