I Would like to have a function being executed in a different thread.
Initially I used a custom object that extended QRunnable
and I would have a QThreadPool
managing it, but I abandoned that approach because I wasn't able to stop the thread execution.
Now I'm trying to execute the function using QThread
. I create a custom object that extend QObject
and contains the function I want to be executed and I connect the QThread.started
signal to Updater.activity
(where Updater
is the custom class I created).
Inside the Updater
I also created a Signal
that should emit
at the end of the function.
The problem is, nothing happens, I think I'm getting something wrong, but I can't grasp it.
Thanks in advance.
Here's the code:
from PySide6.QtWidgets import QPushButton, QWidget, QVBoxLayout, QMainWindow, QApplication
from PySide6.QtCore import QThread, Signal, QObject
import sys
class Updater(QObject):
finished = Signal()
def __init__(self, parent = None):
super(Updater, self).__init__(parent)
def activity(self):
print("CIAO")
self.finished.emit()
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.thread = QThread()
# main button
self.addButton = QPushButton('button to start thread')
self.addButton.clicked.connect(self.button_clicked)
self.mainLayout = QVBoxLayout()
# add all main to the main vLayout
self.mainLayout.addWidget(self.addButton)
self.centralWidget = QWidget()
self.centralWidget.setLayout(self.mainLayout)
self.setCentralWidget(self.centralWidget)
def button_clicked(self):
updater = Updater()
updater.moveToThread(self.thread)
self.thread.started.connect(updater.activity)
updater.finished.connect(self.thread.quit)
updater.finished.connect(self.finish_msg)
print("Starting the Thread")
self.thread.start()
def finish_msg(self):
print("Finished")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
CodePudding user response:
Thank to @musicamante I understood.
I just needed to use self.updater
instead of updater
to prevent it to be garbage collected.