0

我有以下功能,QTimer用于每秒更新counter一次1

def somefunc(): 
  if self.pushButton_13.text() == 'OFF':
            self.pushButton_13.setText('ON')
            timer1.setInterval(1000) #timer1 is global variable
            timer1.timeout.connect(lambda: self.counter(15))
            timer1.start()
  else:
            self.pushButton_13.setText('OFF')
            timer1.stop()
            print timer1.timerId()

def counter(self, var):
    if var == 15:
        count = int(str(self.lineEdit_15.text()))

        count = count + 1
        print count
        self.lineEdit_15.setText(QtCore.QString(str(count)))

当我第一次按下按钮counter工作正常但如果再次单击按钮停止计时器然后再次重新启动时,计数器值2每秒更新一次1- 而应该更新1. 同样,如果我再次单击按钮以停止计数器并再次重新启动,则计数器更新3等等。我在哪里犯错?

4

1 回答 1

1

每次按下按钮时,您都会建立新的连接,这与之前的连接无关。这会导致counter插槽被多次调用,每个连接调用一次。来自 Qt 的文档

您建立的每个连接都会发出一个信号,因此重复的连接会发出两个信号。您可以使用 disconnect() 断开连接。

您应该只设置一次(即创建它并连接timeout到适当的插槽)计时器一次,然后再start设置stop它所需的次数。

或者,您的代码最简单的解决方案是:

        #...
        timer1.setInterval(1000)  
        timer1.disconnect()       # removes previous connections
        timer1.timeout.connect(lambda: self.counter(15))
        timer1.start()
        #...
于 2013-12-13T12:50:08.730 回答