Addressing concerns of "duplicate question" - thank you for properly reading my question:
- Cannot terminate PyQT QThread - Uses terminate(), something I clearly said that I do not want to use because it is not safe
- How to stop QThread "gracefully"? - Uses a flag, something I clearly said that I do not want to use because the real application is not a simple loop
- Stopping an infinite loop in a worker thread in PyQt5 the simplest way - The real application is not a simple loop
Find below a simple full working example of a problem I am facing. I am trying to figure out how to properly use QThreads, and following some common advice I am using the moveToThread function. However, despite this, when I call quit on the thread, it seemingly does not do anything (it keeps printing).
import sys
import time
from PySide6.QtCore import QThread, Signal, QEventLoop, QObject
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
class Worker(QObject):
finished = Signal()
def long_task(self):
i=0
while i<1000:
i+=1
print("Hello World")
time.sleep(1)
self.finished.emit()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PySide6 Thread Example")
self.setGeometry(100, 100, 300, 200)
self.button = QPushButton("Stop Thread", self)
self.button.setGeometry(100, 100, 100, 50)
self.button.clicked.connect(self.stop_thread)
self.thread1 = QThread(self)
self.worker = Worker()
self.worker.moveToThread(self.thread1)
self.thread1.started.connect(self.worker.long_task)
self.worker.finished.connect(self.thread1.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread1.finished.connect(self.thread1.deleteLater)
self.thread1.start()
def stop_thread(self):
self.thread1.exit()
# self.thread1.quit()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Pressing the button will not stop the worker. Is there a way to make this work under the following conditions?
- Without using terminate()
- Without using flags
- Without using "short tasks" (what is the point of exit then, if you have to wait for the work to be done anyway?)
I am guessing I am doing something wrong - or maybe I am following the complete wrong approach.