I'm currently trying to build a PyQt5 app and it should consist of the main GUI and in the background there should be a different thread that should measure something in an infinite loop. And I want to start and stop this thread using a QAction or Checkbox.
So to say when I press the checkbox and the state is true the thread should be started and if I click it again it should be stopped.
Now what is the best way to implement this?
Currently I'm using a Worker thread like this:
class Worker(QtCore.QObject):
def __init__(self):
super(Worker, self).__init__()
self._isRunning = True
def task(self):
if not self._isRunning:
self._isRunning = True
while self._isRunning:
time.sleep(0.5)
... measure ...
def stop(self):
self._isRunning = False
and this in the main thread to make it run:
self.thread = QtCore.QThread()
self.thread.start()
self.worker = Worker()
self.worker.moveToThread(self.thread)
self.btn_start.clicked.connect(self.worker.task)
self.btn_stopped.clicked.connect(lambda: self.worker.stop())
So far this works. But I'm not really confident that this is the best way to do it and I'd also like it much better if I could make the same thing using a checkbox in the way described.