Skip to content

Instantly share code, notes, and snippets.

@ShenTengTu
Created March 24, 2024 05:56
Show Gist options
  • Save ShenTengTu/e3a0d4e15e9484297c341bd4918a66bc to your computer and use it in GitHub Desktop.
Save ShenTengTu/e3a0d4e15e9484297c341bd4918a66bc to your computer and use it in GitHub Desktop.
Function that generates a stylesheet for styling QPushButton
import sys
from qtpy.QtWidgets import (
QApplication,
QMainWindow,
QPushButton,
QFrame,
QGridLayout,
)
def style_QPushButton(
border_color: str = "#b0b0b0",
bg_color: str = "#e0e0e0",
fg_color: str = "#404040",
border_width: str = "1px",
border_radius: str = "4px",
horizontal_padding: str = "4px",
vertical_padding: str = "2px",
state_styles: dict[str, dict[str, str]] = {
"hover": {
"border_color": "#404040",
},
"pressed": {
"bg_color": "#b0b0b0",
},
"disabled": {
"border_color": "#b0b0b0",
"bg_color": "#f0f0f0",
"fg_color": "#b0b0b0",
},
"checked": {
"border_color": "#2020ff",
"bg_color": "#e0e0f0",
"fg_color": "#404080",
},
"checked:hover": {
"border_color": "#404040",
},
"checked:pressed": {
"bg_color": "#b0b0b0",
},
},
):
qss = f"""
QPushButton {{
border-width: {border_width};
border-style: solid;
border-color: {border_color};
border-radius: {border_radius};
background-color: {bg_color};
color: {fg_color};
padding: {vertical_padding} {horizontal_padding};
}}
"""
for state, styles in state_styles.items():
rules = []
if "border_color" in styles:
rules.append(f"border-color: {styles['border_color']};")
if "bg_color" in styles:
rules.append(f"background-color: {styles['bg_color']};")
if "fg_color" in styles:
rules.append(f"color: {styles['fg_color']};")
if rules:
rules_str = "\n".join(rules)
qss += f"""
QPushButton:{state} {{
{rules_str}
}}
"""
return qss
class Frame(QFrame):
def __init__(self, parent=None):
super().__init__(parent)
layout = QGridLayout()
layout.setSizeConstraint(QGridLayout.SizeConstraint.SetFixedSize)
w = QPushButton("Button")
layout.addWidget(w, 0, 0)
w = QPushButton("Button disabled")
w.setDisabled(True)
layout.addWidget(w, 0, 1)
w = QPushButton("Checkable Button")
w.setCheckable(True)
w.setChecked(True)
layout.addWidget(w, 1, 0)
self.setLayout(layout)
def main():
app = QApplication(sys.argv)
app.setStyleSheet(style_QPushButton())
w = QMainWindow()
w.setMinimumSize(200, 100)
w.setCentralWidget(Frame(w))
w.show()
sys.exit(app.exec())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment