Using Python 3.7 and PySide2, I created a worker object on a dedicated QThread to execute a long-running function. This is illustrated in the code below.
import threading
from time import sleep
from PySide2.QtCore import QObject, QThread, Signal, Slot
from PySide2.QtWidgets import QApplication
class Main(QObject):
signal_for_function = Signal()
def __init__(self):
print('The main thread is "%s"' % threading.current_thread().name)
super().__init__()
self.thread = QThread(self)
self.worker = Worker()
self.worker.moveToThread(self.thread)
self.thread.start()
self.signal_for_function.connect(self.worker.some_function)
def some_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
class Worker(QObject):
# @some_decorator
def some_function(self):
print('some_function is running on thread "%s"' % threading.current_thread().name)
app = QApplication()
m = Main()
m.signal_for_function.emit()
sleep(0.100)
m.thread.quit()
m.thread.wait()
If I use some_function without the decorator, I get this as expected:
The main thread is "MainThread"
some_function is running on thread "Dummy-1"
However, if I apply a decorator (i.e. uncomment "@some_decorator"), I get:
The main thread is "MainThread"
some_function is running on thread "MainThread"
Why does this happen, and how do I make the decorated function run on the worker thread as I intented to?