Hi
In PyQt5, we will consider another widget, groupbutton the QButtonGroup() class.
Ideal for use when we can combine different buttons in the same selection category.
As an example, we have 3 buttons named save, save as, exit without save.
We can use groupbutton here because its work is different but similar in category.
Our Example :
This is how we define our groubutton.
self.group_button = QButtonGroup()
We defined the method to be triggered when any of the buttons are clicked
self.group_button.buttonClicked[int].connect(self.handleClickGroupButton)
We added our widgets to our layout.
my_vertical_layout = QVBoxLayout() my_vertical_layout.addWidget(self.btn_save) my_vertical_layout.addWidget(self.btn_save_and_exit) my_vertical_layout.addWidget(self.btn_exit_without_save) my_vertical_layout.addWidget(self.result_label)
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.group_button = QButtonGroup() self.group_button.buttonClicked[int].connect(self.handleClickGroupButton) self.btn_save = QPushButton("Save") self.group_button.addButton(self.btn_save,1) self.btn_save_and_exit = QPushButton("Save And Exit") self.group_button.addButton(self.btn_save_and_exit,2) self.btn_exit_without_save = QPushButton("Exit Without Save") self.group_button.addButton(self.btn_exit_without_save,3) self.result_label = QLabel("") my_vertical_layout = QVBoxLayout() my_vertical_layout.addWidget(self.btn_save) my_vertical_layout.addWidget(self.btn_save_and_exit) my_vertical_layout.addWidget(self.btn_exit_without_save) 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 handleClickGroupButton(self,button_id): for btn in self.group_button.buttons(): if btn is self.group_button.button(button_id): self.result_label.setText("Clicked Button: " + btn.text()) app = QApplication(sys.argv) win = MainFrame() sys.exit(app.exec_())