在设置定时器,一定要设置固定时间,才精准,过大或者过小都会导致时间不精准
self.timer.setInterval(1000) # 设置更新频率,单位为毫秒
self.timer.start()
示例:运行1分钟,做进度条
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QProgressBar
from PyQt5.QtCore import QTimer, QDateTime, QTime
from datetime import datetime
class ProgressBarWindow(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setWindowTitle('Progress Bar Example')
layout = QVBoxLayout()
# 创建进度条和按钮
self.progress_bar = QProgressBar()
self.progress_bar.setValue(0)
layout.addWidget(self.progress_bar)
self.start_button = QPushButton('Start')
self.start_button.clicked.connect(self.start_progress)
layout.addWidget(self.start_button)
self.setLayout(layout)
def start_progress(self):
self.start_time = QDateTime.currentDateTime()
self.duration = 60 # 1分钟
self.timer = QTimer()
self.timer.timeout.connect(self.update_progress)
self.timer.start(1000) # 每秒更新一次
def update_progress(self):
current_time = QDateTime.currentDateTime()
print(current_time, datetime.now().strftime("%H:%M:%S.%f"))
elapsed = self.start_time.secsTo(current_time)
print(elapsed)
progress = (elapsed / self.duration) * 100
self.progress_bar.setValue(progress)
if elapsed >= self.duration:
self.timer.stop()
self.progress_bar.setValue(100)
print("Task Completed!")
def main():
app = QApplication(sys.argv)
window = ProgressBarWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()