PyQt5 - Setting background color to the indicator of radio button when it get pressed

PyQt5 - Setting background color to the indicator of radio button when it get pressed

To set the background color to the indicator of a QRadioButton in PyQt5 when it gets pressed, you'll use Qt Style Sheets (QSS). QSS provides a way to style Qt widgets similar to how CSS styles HTML elements.

Here's an example of how to set the background color of a QRadioButton's indicator when it's pressed:

import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QRadioButton class AppDemo(QWidget): def __init__(self): super().__init__() self.resize(300, 200) layout = QVBoxLayout() radio1 = QRadioButton("Option 1") radio2 = QRadioButton("Option 2") radio3 = QRadioButton("Option 3") layout.addWidget(radio1) layout.addWidget(radio2) layout.addWidget(radio3) self.setLayout(layout) # Style the radio buttons style = """ /* Style the indicator of the radio button */ QRadioButton::indicator { width: 20px; height: 20px; border: 1px solid gray; border-radius: 10px; } /* Set the background color when pressed */ QRadioButton::indicator:pressed { background-color: lightblue; } /* Set the background color when checked */ QRadioButton::indicator:checked { background-color: blue; } """ self.setStyleSheet(style) app = QApplication(sys.argv) demo = AppDemo() demo.show() sys.exit(app.exec_()) 

In the above code:

  • We first style the QRadioButton::indicator to make it larger and round with a gray border.
  • Next, we set the background color of the indicator to lightblue when it's pressed using QRadioButton::indicator:pressed.
  • We also provide a style for the checked state (QRadioButton::indicator:checked) to differentiate between the pressed and checked states.

Run the code, and when you press (click down) on the radio button, the indicator will temporarily show a lightblue background. When you release the mouse button, if the radio button gets selected (checked), the background color of the indicator will change to blue.


More Tags

tmp mode docker-image masked-array scope ngtools sql-server-2016 synchronization project-reactor firefox-addon

More Programming Guides

Other Guides

More Programming Examples