from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction class MainWindow(QMainWindow): def __init__(self): super().__init__() # create a menu object menu = QMenu(self) # create some action objects new_action = QAction("New", self) open_action = QAction("Open", self) save_action = QAction("Save", self) # add the actions to the menu menu.addAction(new_action) menu.addAction(open_action) menu.addAction(save_action) # show the menu at a specific position menu.exec_(self.mapToGlobal(self.cursor().pos())) if __name__ == "__main__": app = QApplication([]) window = MainWindow() window.show() app.exec_()
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction class MainWindow(QMainWindow): def __init__(self): super().__init__() # set the context menu policy for the window self.setContextMenuPolicy(Qt.CustomContextMenu) # create the context menu object self.context_menu = QMenu(self) # create some actions for the context menu cut_action = QAction("Cut", self) copy_action = QAction("Copy", self) paste_action = QAction("Paste", self) # add the actions to the context menu object self.context_menu.addAction(cut_action) self.context_menu.addAction(copy_action) self.context_menu.addAction(paste_action) # connect the 'customContextMenuRequested' signal to show_context_menu() method self.customContextMenuRequested.connect(self.show_context_menu) def show_context_menu(self, event): # show the context menu at the position of the mouse self.context_menu.exec_(self.mapToGlobal(event.pos())) if __name__ == "__main__": app = QApplication([]) window = MainWindow() window.show() app.exec_()This code creates a context menu for the window with three QAction objects and displays it when the user right-clicks on the window. The context menu is displayed at the position of the mouse.