If I create an application with a MainWindow and a QDialog and then open and close the dialog the main window remains open.
But if my QDialog starts a thread, and once this thread is finished I close the QDialog then my whole application closes.
On the simple app below you can reproduce my problem. It's ok if I open the dialog and close without launch the tread. But if I launch the thread and close the dialog after finished the application terminate.
Can you tell me where is my mistake?
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QPushButton, QVBoxLayout
from PyQt5.QtCore import QThread, QObject, pyqtSignal
from time import sleep
from PyQt5.Qt import QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
button = QPushButton("Press me for a dialog!")
button.clicked.connect(self.button_clicked)
self.setCentralWidget(button)
def button_clicked(self):
my_dialog = myDialog(parent=self)
my_dialog.exec()
class myDialog(QDialog):
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.setWindowTitle('My dialog')
self.button = QPushButton("Run long task")
self.button.clicked.connect(self.run_long_task)
self.message = QLabel("Long task not launched")
self.layout = QVBoxLayout()
self.layout.addWidget(self.button)
self.layout.addWidget(self.message)
self.setLayout(self.layout)
def run_long_task(self):
self.message.setText('Long task running')
self.thread = QThread()
self.worker = LongTask()
self.worker.long_task_finished.connect(self.long_task_finished)
self.thread.started.connect(self.worker.work)
self.worker.moveToThread(self.thread)
self.thread.start()
def long_task_finished(self):
self.message.setText('Long task finished')
class LongTask(QObject):
long_task_finished = pyqtSignal()
def work(self):
sleep(5)
self.long_task_finished.emit()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Thanks for your help.