python pyqt5 踩坑

在设置定时器,一定要设置固定时间,才精准,过大或者过小都会导致时间不精准

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()

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值