锋哥原创的PyQt6视频教程:
2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~共计52条视频,包括:2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~、第2讲 PyQt6库和工具库QTDesigner安装与配置、第3讲 PyQt6第一个程序HelloWorld实现等,UP主更多精彩视频,请关注UP账号。https://www.bilibili.com/video/BV11C4y1P7fj/
在PyQt6中,如果需要周期性地执行某项操作,就可以使用QTimer类实现,QTimer类表示计时器,它可以定期发射timeout信号,时间间隔的长度在start()方法中指定,以毫秒为单位,如果要停止计时器,则需要使用stop()方法。
我们做一个 显示当前日期时间的程序:
UI生成参考代码:
from PyQt6 import QtCore, QtGui, QtWidgetsclass Ui_Form(object):def setupUi(self, Form):Form.setObjectName("Form")Form.resize(400, 300)self.pushButton = QtWidgets.QPushButton(parent=Form)self.pushButton.setGeometry(QtCore.QRect(60, 90, 75, 23))self.pushButton.setObjectName("pushButton")self.pushButton_2 = QtWidgets.QPushButton(parent=Form)self.pushButton_2.setGeometry(QtCore.QRect(190, 90, 75, 23))self.pushButton_2.setObjectName("pushButton_2")self.label = QtWidgets.QLabel(parent=Form)self.label.setGeometry(QtCore.QRect(70, 170, 53, 15))self.label.setText("")self.label.setObjectName("label")self.retranslateUi(Form)QtCore.QMetaObject.connectSlotsByName(Form)def retranslateUi(self, Form):_translate = QtCore.QCoreApplication.translateForm.setWindowTitle(_translate("Form", "Form"))self.pushButton.setText(_translate("Form", "Start"))self.pushButton_2.setText(_translate("Form", "Stop"))
Main测试代码:
"""python加载ui文件作者 : 小锋老师官网 : www.python222.com
"""
import sysfrom PyQt6.QtCore import QTimer, QDateTime
from PyQt6.QtWidgets import QApplication, QLabel, QPushButton
from PyQt6 import uicdef f1(label: QLabel):time = QDateTime.currentDateTime()timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss");label.setText(timeDisplay)def start(timer, label):timer.start(1000)timer.timeout.connect(lambda: f1(label))def stop(timer):timer.stop()if __name__ == '__main__':app = QApplication(sys.argv)ui = uic.loadUi("./QTimer计时器控件.ui")timer = QTimer(ui)pushButton: QPushButton = ui.pushButtonpushButton_2: QPushButton = ui.pushButton_2label: QLabel = ui.labelpushButton.clicked.connect(lambda: start(timer, label))pushButton_2.clicked.connect(lambda: stop(timer))ui.show()sys.exit(app.exec())