Friday, November 15, 2024
Google search engine
HomeLanguagesPyQt5 QCalendarWidget – Setting Key Press Event

PyQt5 QCalendarWidget – Setting Key Press Event

In this article we will see how we can implement the key press event for the QCalendarWidget. In order to set the key press event we have to override the keyPressEvent method, by overriding the key press event we can add functions to the calendar whenever the key is pressed.

Implementation steps:
1. Create a main window
2. Create a QCalendarWidget
3. Set various properties to the calendar
4. Override the keyPressEvent
5. Inside the override method check if the escape key pressed then show the today in calendar

Below is the implementation

Python3




# importing libraries
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
import sys
  
  
class Window(QMainWindow):
  
    def __init__(self):
        super().__init__()
  
        # setting title
        self.setWindowTitle("Python ")
  
        # setting geometry
        self.setGeometry(100, 100, 650, 400)
  
        # calling method
        self.UiComponents()
  
        # showing all the widgets
        self.show()
  
    # method for components
    def UiComponents(self):
  
        # creating a QCalendarWidget object
        self.calendar = QCalendarWidget(self)
  
        # setting geometry to the calendar
        self.calendar.setGeometry(50, 10, 400, 250)
  
        # setting cursor
        self.calendar.setCursor(Qt.PointingHandCursor)
  
  
    # overriding key press event
    def keyPressEvent(self, e):
  
        # when escape key is pressed
        if e.key() == Qt.Key_Escape:
  
            # show the present date
            self.calendar.showToday()
            print("Calendar Show Today")
  
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
  
# start the app
sys.exit(App.exec())


Output:

Calendar Show Today
Calendar Show Today
Calendar Show Today
Calendar Show Today

Whenever the escape key is pressed it shows the today(present date page)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments