PyQt5 QCalendarWidget – 设置按键事件
在本文中,我们将了解如何为 QCalendarWidget 实现按键事件。为了设置按键事件,我们必须重写 keyPressEvent 方法,通过重写按键事件,我们可以在按键被按下时向日历添加功能。
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
下面是实现
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())
输出:
Calendar Show Today
Calendar Show Today
Calendar Show Today
Calendar Show Today
每当按下退出键时,它都会显示今天(当前日期页面)