- 显示当前时间
主要内容 #
完成效果 #
本节课程是万年历实现的第三节,完成本节课程,能实现使用标签控件实时显示当前的时间。
收获 #
学习完本节内容,我们会创建标签来显示实时日期以及时分秒信息,并逐秒更新时间。
1.显示当前时间 #
QDateTime.currentDateTime()能获取当前时间,然后可以将时间按指定格式显示在标签上。
QTimer倒计时器,设置超时时间为1000毫秒也就是1秒,表示每隔一秒钟倒计时器就会触发超时信号。
超时信号与槽函数showTime相连,显示当前时间,逐秒更新。以下就是本例代码:
from PyQt5.QtWidgets import QWidget, QCalendarWidget, QLabel, QApplication, QVBoxLayout from PyQt5.QtCore import QDate, QDateTime, QTimer, Qt import sys class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QVBoxLayout(self) # 创建一个垂直盒布局 cal = QCalendarWidget(self) # 创建一个日历对象 cal.setNavigationBarVisible(True) # 设置导航条是否可见,True为可见 cal.setFirstDayOfWeek(Qt.Monday) # 设置周一为每周的第一天 cal.setGridVisible(True) # 显示网格线 cal.setDateRange(QDate(1949, 1, 1), QDate(2049, 1, 1)) # 设置日历涵盖的日期范围,从1949.1.1-2049.1.1 self.lbl = QLabel(self) # 创建一个标签 # 选择一个日期时,clicked的点击信号就触发了,与showdate槽函数相关联并传入QDate参数。 cal.clicked[QDate].connect(self.showDate) vbox.addWidget(cal) # 将日历添加到布局中 vbox.addWidget(self.lbl) # 将标签添加到布局中 self.lbl2 = QLabel(self) # 再创建一个标签,显示当前的时分秒信息 self.timer = QTimer(self) # 创建一个定时器实例 self.timer.timeout.connect(self.showTime) # 计时结束时,触发timeout超时信号,并连接到槽函数showTime vbox.addWidget(self.lbl2) # 将标签添加到布局中 self.timer.start(1000) # 启动计时器,并设置超时时间为1000毫秒也即1秒 self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Calendar') self.show() def showDate(self, date): # 获取选中的日期,然后把日期对象转成字符串,在标签里面显示出来 self.lbl.setText(date.toString()) def showTime(self): # QDateTime.currentDateTime()能获取当前时间 time = QDateTime.currentDateTime() # toString()方法将当前时间按指定格式转换为字符串 # yyyy/MM/dd 分别对应年月日,HH:mm:ss分别对应时分秒,dddd表示星期 self.lbl2.setText('当前时间:' + time.toString("yyyy/MM/dd HH:mm:ss dddd")) # 让标签显示当前时间 app = QApplication(sys.argv) # 创建应用程序 ex = Example() # 创建窗口对象 sys.exit(app.exec_()) # 设置关闭窗口后结束进程
拓展练习:尝试将当前时间的显示格式改为”yyyy-MM-dd HH:mm:ss”。
小结 #
习题 #
- 习题1:尝试将QTimer的超时时间改为3000毫秒,让时间每三秒更新一次。