Hi
As you know, Radiobutton is a very useful element.What it is used for: Ideal for use in questions where multiple options are asked.
Of course it can also be used for many other purposes.
Now i will make an example.In our example, we will use the radio together in the QVBoxLayout class in order to use it more clearly.
What will this do for us? To align the radio and the ones we use with it vertically.It also has a horizontal class, the QHBoxLayout class.
First of all
I write the components that I will use in the visual.
self.title_label = QLabel('Gender ?') self.radio_btn1 = QRadioButton("Man") self.radio_btn2 = QRadioButton("Woman") #result label self.result_label = QLabel("")
#I set the method to be triggered when any of the radio buttons are selected, i.e. when it is toggle self.radio_btn1.toggled.connect(self.handleRadioResult) self.radio_btn2.toggled.connect(self.handleRadioResult)
#I create a vertical layout. and I add the components that I will use in the visual. my_vertical_layout = QVBoxLayout() my_vertical_layout.addWidget(self.title_label) my_vertical_layout.addWidget(self.radio_btn1) my_vertical_layout.addWidget(self.radio_btn2) my_vertical_layout.addWidget(self.result_label)
Here, the method to be triggered when one of the radios is selected. I get the value of the radio currently selected with self.sender (). and I’m writing on the result label
def handleRadioResult(self): handle_radio = self.sender() if handle_radio.isChecked(): self.result_label.setText("Selected gender: " + handle_radio.text())
Result:
Full source code:
from PyQt5.QtWidgets import * import sys W_WIDTH = 400 W_HEIGHT = 250 W_X = 400 W_Y = 150 class MainFrame(QWidget): def __init__(self): super().__init__() self.init() def init(self): self.title_label = QLabel('Gender ?') self.radio_btn1 = QRadioButton("Man") self.radio_btn2 = QRadioButton("Woman") #result label self.result_label = QLabel("") self.radio_btn1.toggled.connect(self.handleRadioResult) self.radio_btn2.toggled.connect(self.handleRadioResult) my_vertical_layout = QVBoxLayout() my_vertical_layout.addWidget(self.title_label) my_vertical_layout.addWidget(self.radio_btn1) my_vertical_layout.addWidget(self.radio_btn2) my_vertical_layout.addWidget(self.result_label) self.setGeometry(W_WIDTH, W_HEIGHT, W_X, W_Y) self.setLayout(my_vertical_layout) self.setWindowTitle("www.langpy.com | Python GUI Tutorial") self.show() def handleRadioResult(self): handle_radio = self.sender() if handle_radio.isChecked(): self.result_label.setText("Selected gender: " + handle_radio.text()) app = QApplication(sys.argv) win = MainFrame() sys.exit(app.exec_())