【问题标题】:QTimer singleShot with variables and that can be stopped带有变量的 QTimer singleShot 并且可以停止
【发布时间】:2021-03-12 11:28:45
【问题描述】:

我希望延迟 gui 中的函数,但涉及参数。 我尝试在 singleShot 上运行 lambda,但是事先创建了 QTimer,这样我也可以停止它,但似乎不起作用。

在我的班级init

self.timer = QTimer(self)

调用计时器:

self.timer.singleShot(3000, lambda: self.send_message('Hey folks'))

如果需要,我也希望能够调用 .stop。

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    您根本没有使用您创建的计时器实例:您实际上是在调用 static singleShot 方法,该方法会立即创建并启动一个新的 singleShot-QTimer,因为有没有参考那个计时器,你不能停止它。

    您应该将 singleShot 属性设置为 现有 计时器实例:

    self.timer = QTimer(self)
    self.timer.setSingleShot(True)
    
    # alternatively:
    self.timer = QTimer(self, singleShot=True)
    

    如果你需要不断改变超时的目标,你可以调用一个通用的self.timer.disconnect()(可能在try块内,以防之前没有建立连接),并按顺序创建对该函数的引用断开它:

        try:
            self.timer.timeout.disconnect(self.delayedFunction)
        except:
            pass
    
        def wrapper():
            self.send_message('Hey folks')
            self.timer.timeout.disconnect(wrapper)
    
        self.delayedFunction = wrapper
        self.timer.timeout.connect(self.delayedFunction)
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多