PyQt5 QCalendarWidget - Adding Multiple QAction

PyQt5 QCalendarWidget - Adding Multiple QAction

To add multiple QAction to a QCalendarWidget in PyQt5, you can use the context menu of the widget. You can either use the default context menu (by adding actions) or implement a custom context menu.

Here's an example to illustrate adding multiple QAction to a QCalendarWidget using a custom context menu:

import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QCalendarWidget, QMenu from PyQt5.QtCore import Qt class AppDemo(QWidget): def __init__(self): super().__init__() self.resize(400, 300) layout = QVBoxLayout() self.calendar = QCalendarWidget(self) # Set the context menu policy to custom self.calendar.setContextMenuPolicy(Qt.CustomContextMenu) self.calendar.customContextMenuRequested.connect(self.show_context_menu) layout.addWidget(self.calendar) self.setLayout(layout) def show_context_menu(self, position): # Create a context menu and add actions contextMenu = QMenu(self) action1 = contextMenu.addAction("Action 1") action2 = contextMenu.addAction("Action 2") # Connect actions to slots action1.triggered.connect(self.action1_triggered) action2.triggered.connect(self.action2_triggered) # Show the context menu at the requested position contextMenu.exec_(self.calendar.mapToGlobal(position)) def action1_triggered(self): print("Action 1 triggered") def action2_triggered(self): print("Action 2 triggered") app = QApplication(sys.argv) demo = AppDemo() demo.show() sys.exit(app.exec_()) 

In this example:

  1. We set the context menu policy of the QCalendarWidget to Qt.CustomContextMenu to create a custom context menu.
  2. We connected the customContextMenuRequested signal to the show_context_menu slot. This slot will be called when a context menu request is made (i.e., when you right-click on the calendar).
  3. Inside the show_context_menu slot, we created a QMenu, added two QAction to it, and then displayed the menu at the requested position.
  4. We also connected the triggered signal of each action to custom slots (action1_triggered and action2_triggered) which will be executed when the corresponding action is selected.

When you right-click on the calendar, a context menu with two actions will appear. Clicking on an action will execute its corresponding slot.


More Tags

formatted-input apache-spark-ml bpmn sqlcmd custom-formatting null-pointer wikipedia-api aws-glue frame-rate ioerror

More Programming Guides

Other Guides

More Programming Examples