PyQt5 QCalendarWidget – 检查其是否拥有焦点
在这篇文章中,我们将看到我们如何检查QCalendarWidget是否有焦点。焦点基本上是输入的焦点,默认情况下,它没有焦点,但是当应用程序被执行时,鼠标点击它,它就会得到焦点,但是当鼠标点击其他小部件时,它的焦点会被转移。
为了做到这一点,我们将使用QCalendarWidget对象的hasFocus方法。
语法: calendar.hasFocus()
参数: 它不需要参数
返回: 它返回bool
实现步骤:
1.创建一个主窗口
2.创建一个日历小部件
3.在不同的位置创建一个行编辑小组件
4.创建一个标签来显示焦点状态
5.创建QTimer对象,每隔200毫秒调用一次动作
6.在定时器动作中检查日历的焦点
以下是实施过程
# 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)
# creating label to show the properties
self.label = QLabel(self)
# setting geometry to the label
self.label.setGeometry(100, 280, 250, 60)
# making label multi line
self.label.setWordWrap(True)
# checking edit focus
value = self.calendar.hasFocus()
# setting text to the label
self.label.setText("Has Focus : " + str(value))
# creating a timer object
timer = QTimer(self)
timer.timeout.connect(self.show_time)
timer.start(200)
# creating a line edit
line = QLineEdit(self)
# setting geometry to the line edit
line.setGeometry(500, 100, 100, 40)
# method called by the timer
def show_time(self):
# checking focus
value = str(self.calendar.hasFocus())
# setting text through label
self.label.setText("Has Focus : " + value)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())