Pregunta

I have the following function where I am using QTimer to update my counter after every 1 second:

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

When I first press button counter is working properly but if click button again to stop timer and then again restart, the counter value updates by 2 for every 1 second - instead it should be updated by 1. Similarly if I again click the button to stop the counter and again restart then counter updates by 3 and so on. Where I am making mistake?

¿Fue útil?

Solución

Every time you press the button you make a new connection, that is independent to the previous ones. This causes that the counter slot is called multiple number of times, once for each connection. From Qt's documentation:

Every connection you make emits a signal, so duplicate connections emit two signals. You can break a connection using disconnect().

You should set up (i.e. create it and connect timeout to appropriate slots) the timer only once, and then only start and stop it as many times as you need.

Alternatively, the simplest solution for your code is this:

        #...
        timer1.setInterval(1000)  
        timer1.disconnect()       # removes previous connections
        timer1.timeout.connect(lambda: self.counter(15))
        timer1.start()
        #...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top