PyQt5 QCalendarWidget 设置按键事件
在这篇文章中,我们将看到我们如何为QCalendarWidget实现按键事件。为了设置按键事件,我们必须覆盖keyPressEvent方法,通过覆盖按键事件,我们可以在按键被按下时向日历添加功能。
实施步骤:
1.创建一个主窗口
2.创建一个QCalendarWidget
3.为日历设置各种属性
4.覆盖keyPressEvent
5.在覆盖方法中检查是否按下了转义键,然后在日历中显示今天的内容。
下面是实现的过程
# 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
无论何时按下转义键,都会显示今天(当前日期页)。