You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt6中如何在几秒后停止QTimer?

解决方案

不用额外的循环或监控定时器,直接利用Qt提供的QTimer.singleShot()就能实现主定时器的延迟自动停止,这是最符合Qt事件驱动模型的简洁方案。

修改后的代码

import sys
import random
from PyQt5.QtCore import QObject, QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow
# 假设Ui_MainWindow和Utils是你已定义的模块
from your_module import Ui_MainWindow, Utils

class Client(QObject):
    def __init__(self):
        super(Client, self).__init__()
        self._window = QMainWindow()
        self._window.showMaximized()
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self._window)

        name_list = ['A', 'V', 'D', 'E', 'L']
        Utils.set_name_list(name_list)

        self.timer = QTimer()
        self.timer.timeout.connect(self.draw)
        self._ui.pushButton.clicked.connect(self.start)

    def draw(self):
        self._ui.label.setText(random.choice(Utils.name_list()))

    def start(self):
        # 启动主定时器,每隔250ms执行一次draw
        self.timer.start(250)
        # 设置3秒(3000毫秒)后自动停止主定时器,时间可按需调整
        QTimer.singleShot(3000, self.timer.stop)

if __name__ == "__main__":
    application = QApplication(sys.argv)
    client = Client()
    sys.exit(application.exec_())

关键说明

  • QTimer.singleShot()是一个一次性定时器,它会在指定的毫秒数后触发一次目标函数,这里直接绑定主定时器的stop()方法,就能实现自动停止。
  • 这种方式完全由Qt的事件循环处理,不会阻塞主线程,比手动用循环监控时间(比如记录启动时间然后每次draw里判断)更高效、更简洁。
  • 如果需要在停止定时器时执行额外逻辑(比如固定显示最终选中的内容),可以自定义一个停止函数,再把它传给singleShot:
    def stop_timer(self):
        self.timer.stop()
        # 示例:停止后固定显示一个随机选中的结果
        final_name = random.choice(Utils.name_list())
        self._ui.label.setText(final_name)
    
    def start(self):
        self.timer.start(250)
        QTimer.singleShot(3000, self.stop_timer)
    

内容的提问来源于stack exchange,提问作者ReverseEngineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:15:54