I know that in general, QObject() instances should be created in the main thread. I also know that - once created - you can move a QObject() from the main thread to another one:
official Qt docs can be found here
# Worker-object approach
# -----------------------
# Note: these codelines execute in the main thread.
workerThread = QThread()
workerObj = WorkerObj()
workerObj.moveToThread(workerThread)
Currently I am facing the exact opposite problem. I have a QObject() instantiated in a (non-main) QThread. I want to move it to the main thread, like this:
# Move a QObject() to the main thread
# ------------------------------------
# Note: these codelines execute in some QThread
myObj = QObject()
myObj.moveToThread(threading.main_thread())
I get the following error:
TypeError: moveToThread(self, QThread): argument 1 has unexpected type '_MainThread'
I probably get the error because the main thread is not a genuine QThread. What should I do to make it work?
EDIT:
Apparently the answer was right in the documentation of the moveToThread() function. This is pretty embarrassing. My sincere apologies. I'll be more careful next time.
QObject instances can be created in any thread, of course. And they are, and Qt would be quite useless without it. What you're looking for is the global application object - and its thread:
myObj = QObject()
mainThread = QCoreApplication.instance().thread()
myObj.moveToThread(mainThread)
It is undefined behavior to call, from the current thread, any non-thread-safe methods on the object after the moveToThread call. Past this call, the object's non-thread-safe methods can be safely used from the target thread only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With