Kyle Mathew Joeckel Kyle Mathew Joeckel - 5 months ago 8
Python Question

using 'stop button' to quit function

So I'm trying to create a timer or sorts, the start button starts the timer, i need to stop the timer with the stop button and then record the time... I can't seem to figure out how to stop the timer function once its started. Ive tried if statements, disconnect(), and many others...
I realize that there is a timer in qt already but I'm trying to figure it out this way. thanks.

import sys
import time
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("/Users/Home/Desktop/Timer/timer.ui")[0]


class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.startButton.clicked.connect(self.timer)

def timer(self):
timeL = 0
self.stopButton.clicked.connect(False)
while True:
self.timeView.display(timeL)
timeL = timeL + 1
time.sleep(1)
app.processEvents()


app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()

Answer

Use a flag to control the loop. Then reset the flag in the slot connected to the stop button:

        self.startButton.clicked.connect(self.timer)
        self.stopButton.clicked.connect(self.stop)

    def stop(self):
        self._timer_flag = False

    def timer(self):
        timeL = 0
        self._timer_flag = True
        while self._timer_flag:
            self.timeView.display(timeL)
            timeL = timeL + 1
            time.sleep(1)
            app.processEvents()

A QTimer is better, because there is no lag in updating the ui. But you can improve your example by using an inner loop to call processEvents more frequently:

    def timer(self):
        timeL = 0
        self._timer_flag = True
        while self._timer_flag:
            self.timeView.display(timeL)
            timeL = timeL + 1
            for _ in range(10):
                # process events for up to 50 milliseconds
                app.processEvents(QtCore.QEventLoop.AllEvents, 50)
                time.sleep(0.1)
Comments