PyQt5 QCalendarWidget – 设置按键释放事件
在本文中,我们将了解如何为 QCalendarWidget 实现按键释放事件。为了设置按键释放事件,我们必须重写 keyReleaseEvent 方法,通过重写按键释放事件,我们可以在按下按键时向日历添加功能。与按键事件不同,按键释放事件发生在按下的按键被释放时,我们可以说第一次按键事件发生,然后释放事件发生
Implementation steps:
1. Create a main window
2. Create a QCalendarWidget
3. Set various properties to the calendar
4. Override the keyReleaseEvent
5. Inside the override method check if the escape key pressed then hide the 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 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