PyQt5 QCalendarWidget 设置按键释放事件
在这篇文章中,我们将看到我们如何为QCalendarWidget实现按键释放事件。为了设置按键释放事件,我们必须覆盖keyReleaseEvent方法,通过覆盖按键释放事件,我们可以在按下的按键被释放时向日历添加功能。与按键事件不同,按键释放事件是在按键被释放时发生的,我们可以说先发生按键事件,然后再发生释放事件。
实施步骤:
1.创建一个主窗口
2.创建一个QCalendarWidget
3.为日历设置各种属性
4.覆盖keyReleaseEvent
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 release event
def keyReleaseEvent(self, e):
# when escape key is released
if e.key() == Qt.Key_Escape:
# hide the calendar
self.calendar.hide()
print("Escape key released Hide the calendar")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出:
Escape key released Hide the calendar