锋哥原创的PyQt6视频教程:
在PyQt6中,如果需要周期性地执行某项操作,就可以使用QTimer类实现,QTimer类表示计时器,它可以定期发射timeout信号,时间间隔的长度在start()方法中指定,以毫秒为单位,如果要停止计时器,则需要使用stop()方法。
我们做一个 显示当前日期时间的程序:
UI生成参考代码:
from PyQt6 import QtCore, QtGui, QtWidgets
class 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.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Start"))
self.pushButton_2.setText(_translate("Form", "Stop"))
Main测试代码:
"""
python加载ui文件
作者 : 小锋老师
官网 : www.python222.com
"""
import sys
from PyQt6.QtCore import QTimer, QDateTime
from PyQt6.QtWidgets import QApplication, QLabel, QPushButton
from PyQt6 import uic
def 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.pushButton
pushButton_2: QPushButton = ui.pushButton_2
label: QLabel = ui.label
pushButton.clicked.connect(lambda: start(timer, label))
pushButton_2.clicked.connect(lambda: stop(timer))
ui.show()
sys.exit(app.exec())