PyQt5 QCalendarWidget - Inserting Multiple QAction

PyQt5 QCalendarWidget - Inserting Multiple QAction

If you want to insert multiple QAction items (for instance, in a context menu) to a QCalendarWidget, you can achieve this by subclassing QCalendarWidget and reimplementing its contextMenuEvent() method.

Here's a step-by-step guide on how to do this:

  1. Subclass QCalendarWidget and override its contextMenuEvent() method.
  2. Create a QMenu and add multiple QAction items to it.
  3. Connect each QAction to a slot (function) that handles the action.

Here's a working example:

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QCalendarWidget, QMenu, QAction class CustomCalendar(QCalendarWidget): def __init__(self, parent=None): super().__init__(parent) def contextMenuEvent(self, event): context_menu = QMenu(self) # Create multiple QAction items action1 = QAction("Action 1", self) action2 = QAction("Action 2", self) action3 = QAction("Action 3", self) # Connect each QAction to a slot action1.triggered.connect(self.action1_triggered) action2.triggered.connect(self.action2_triggered) action3.triggered.connect(self.action3_triggered) # Add actions to the context menu context_menu.addAction(action1) context_menu.addAction(action2) context_menu.addAction(action3) # Show the context menu context_menu.exec_(event.globalPos()) def action1_triggered(self): print("Action 1 triggered") def action2_triggered(self): print("Action 2 triggered") def action3_triggered(self): print("Action 3 triggered") class AppDemo(QMainWindow): def __init__(self): super().__init__() self.calendar = CustomCalendar(self) self.setCentralWidget(self.calendar) app = QApplication(sys.argv) demo = AppDemo() demo.show() sys.exit(app.exec_()) 

Now, when you right-click on the CustomCalendar widget (which is our subclassed QCalendarWidget), a context menu with three actions will appear. Each action will print a corresponding message to the console when selected.


More Tags

c#-3.0 nss environment backwards-compatibility mouse-cursor unhandled-exception networkx system.net html5-history select

More Programming Guides

Other Guides

More Programming Examples