from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QPushButton class MyDialog(QDialog): def __init__(self): super().__init__() # Create button box with Ok and Cancel buttons button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) # Connect Ok button to a function button_box.accepted.connect(self.accept) # Connect Cancel button to a function button_box.rejected.connect(self.reject) # Add button box to the dialog layout layout = QVBoxLayout() layout.addWidget(button_box) self.setLayout(layout)
from PyQt5.QtWidgets import QMainWindow, QAction, QDialog, QDialogButtonBox class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create a menu item that opens a dialog menu_item = QAction('Open Dialog', self) menu_item.triggered.connect(self.show_dialog) self.menuBar().addAction(menu_item) def show_dialog(self): # Create dialog with Ok and Cancel buttons dialog = QDialog() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, dialog) button_box.accepted.connect(dialog.accept) button_box.rejected.connect(dialog.reject) # Show the dialog and wait for it to close if dialog.exec_() == QDialog.Accepted: print('Ok clicked') else: print('Cancel clicked')This example adds a menu item to a QMainWindow that opens a dialog when clicked. The dialog contains an "Ok" and "Cancel" button using QDialogButtonBox, and the result is printed in the console depending on which button was clicked. Package library: PyQt5