I'm writing a simple stopwatch with python (using pyqt5). So far, start/pause/resume functions are working fine but the problem is when I stop the counter and need to start from 0 a thread can't be started again I tried the subclass from here but it's not working.
import threading
from PyQt5 import QtWidgets
from stpw_ui import Ui_MainWindow
from time import sleep
# code snippet from stack overflow to stop a thread
class StoppableThread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# buttons' actions
self.ui.start.clicked.connect(self.stopwatch)
self.ui.pause.clicked.connect(self.pse)
self.ui.stop.clicked.connect(self.stp)
self.ui.resume.clicked.connect(self.res)
# self.ui.reset.clicked.connect(self.rst)
self.t = StoppableThread(target=self.strt)
def UpdateSec(self,s):
self.ui.seconds.display(s)
def UpdateMin(self,m):
self.ui.minutes.display(m)
def stopwatch(self):
self.ui.stacked_buttons.setCurrentIndex(1)
self.pause = False
self.t.start()
pause = False
second = 0
minute = 0
def setpause(self,x):
self.pause = x
# start
def strt(self):
if (self.pause is True):
sleep(0.1)
while self.second <= 59 and self.pause == False:
self.UpdateSec(self.second)
self.second += 1
sleep(1)
if self.second==59:
self.minute += 1
self.UpdateMin(self.minute)
self.second = 0
self.strt()
# pause
def pse(self):
self.ui.stacked_buttons.setCurrentIndex(2)
self.setpause(True)
# stop
def stp(self):
self.setpause(True)
self.ui.stacked_buttons.setCurrentIndex(0)
self.t.stop()
# resume
def res(self):
self.ui.stacked_buttons.setCurrentIndex(1)
self.setpause(False)
# reset / ignore it for now
# def rst(self):
# self.ui.stacked_buttons.setCurrentIndex(0)
# self.setpause(False)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
So:
- How to make the stop button works? (what I'm doing wrong here?)
- Is there a better/simple approach to make a stopwatch? because I feel like I'm over-complicating it.
The GUI (stpw_ui.py) file is available at https://www.filedropper.com/stpwui