Skip to content

Instantly share code, notes, and snippets.

@Patitotective
Last active June 26, 2024 10:27
Show Gist options
  • Save Patitotective/3310d65115a4c1d7db90df178d01d35b to your computer and use it in GitHub Desktop.
Save Patitotective/3310d65115a4c1d7db90df178d01d35b to your computer and use it in GitHub Desktop.
Minimal example of how to use a custom context menu and add actions to it.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QMenu, QAction
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.text_edit = QTextEdit()
self.text_edit.setContextMenuPolicy(Qt.CustomContextMenu)
self.text_edit.customContextMenuRequested.connect(self.context_menu)
self.setCentralWidget(self.text_edit)
def context_menu(self):
menu = QMenu(self)
action1 = QAction("First option")
action1.triggered.connect(lambda: print("You have clicked the first option"))
action2 = QAction("Second option")
action2.triggered.connect(lambda: print("You have clicked the second option"))
menu.addAction(action1)
menu.addAction(action2)
menu.exec_(QCursor.pos())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
@BerdyAlexei
Copy link

Thanks friend. This helped me a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment