from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QApplication class MyDialog(QDialog): def __init__(self, parent=None): super(MyDialog, self).__init__(parent) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) vbox = QVBoxLayout(self) vbox.addWidget(button_box) if __name__ == '__main__': app = QApplication([]) dialog = MyDialog() dialog.exec_() app.exit()
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QApplication class MyDialog(QDialog): def __init__(self, parent=None): super(MyDialog, self).__init__(parent) button_box = QDialogButtonBox() button_box.addButton("Yes", QDialogButtonBox.YesRole) button_box.addButton("No", QDialogButtonBox.NoRole) button_box.addButton("Cancel", QDialogButtonBox.RejectRole) button_box.button(QDialogButtonBox.Yes).clicked.connect(self.on_yes_clicked) button_box.button(QDialogButtonBox.No).clicked.connect(self.on_no_clicked) button_box.rejected.connect(self.reject) vbox = QVBoxLayout(self) vbox.addWidget(button_box) def on_yes_clicked(self): print("Yes clicked") self.accept() def on_no_clicked(self): print("No clicked") self.accept() if __name__ == '__main__': app = QApplication([]) dialog = MyDialog() dialog.exec_() app.exit()In this example, we create a customized QDialogButtonBox with three buttons: "Yes", "No", and "Cancel". We connect the "Yes" and "No" buttons to custom slots that print messages to the console and also call the QDialog's accept() method. Meanwhile, pressing the "Cancel" button will call the QDialog's reject() method.