In this lesson we want to learn How to Create RadioButton in PySide6, In PySide6, RadioButton is a GUI element that allows users to select a single option from a set of predefined options. RadioButtons are often used in forms and questionnaires to allow users to select their preferences.
So this is the complete code for How to Create RadioButton in PySide6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from PySide6.QtWidgets import QApplication, QWidget, QRadioButton class RadioButtonsWindow(QWidget): def __init__(self): super().__init__() # Set window title and geometry self.setWindowTitle('GeeksCoders - RadioButtons') self.setGeometry(100, 100, 300, 200) # Create a QRadioButton object and set its label text self.radio_button1 = QRadioButton('Option 1') self.radio_button2 = QRadioButton('Option 2') # Set the parent widget for the radio buttons self.radio_button1.setParent(self) self.radio_button2.setParent(self) # Move the radio buttons to the desired location self.radio_button1.move(50, 50) self.radio_button2.move(50, 80) # Connect the radio buttons to a slot that will handle the clicked signal self.radio_button1.clicked.connect(self.handle_radio_button_clicked) self.radio_button2.clicked.connect(self.handle_radio_button_clicked) def handle_radio_button_clicked(self): # Get the text of the radio button that was clicked sender = self.sender() radio_button_text = sender.text() # Display the text in the console print(f'{radio_button_text} was clicked') if __name__ == '__main__': # Create the application and window objects app = QApplication([]) window = RadioButtonsWindow() # Show the window and start the event loop window.show() app.exec() |
RadioButtonsWindow class extends from QWidget and overrides its __init__ method to create window with two radio buttons, ‘Option 1’ and ‘Option 2’. handle_radio_button_clicked method is called whenever either of the radio buttons is clicked, and it prints the text of the radio button that was clicked to the console.
The if __name__ == ‘__main__’ block creates the application and window objects, shows the window, and starts the event loop.
Run the complete code and this will be the result