How to properly use QThread in Maya for multi-threading?

Hello everyone,

Recently, I’m working on my own c++ plugin with QThread.

I want to do some heavy calculating work on a sub-thread and updating the progressbar in the main UI by signal and slot.

I use the moveToThread method of QObject and it doesn’t work as expected. It doesn’t run the calculating work.

How to use it properly?

Can anyone give me a simple example ?

Thank you very much.

Yours,

Yixiong Xu

When I did some UI stuff while using threading I subClassed QThread. I’ve seen ppl say its not the best thing to do, but worked fine for me. Here’s a quick snippet :slight_smile:

class WorkerThread(QtCore.QThread):
	progress_signal = QtCore.Signal(str)
	is_running_signal = QtCore.Signal(bool)
	is_complete_signal = QtCore.Signal()

	def __init__(self, parent=None):
		super(WorkerThread, self).__init__(parent)

	def run(self):
		self.is_running_signal.emit(True)

		# Do stuff
		progress_signal = QtCore.Signal(str)


		self.is_running_signal.emit(False)
		self.is_complete_signal.emit()

def reportProgress():
	pass

def finished():
	pass


def doStuff():

	self.worker = WorkerThread(self)

	self.worker.progress_signal.connect(reportProgress)
	# set worker args and things here
	self.worker.is_complete_signal.connect(finished)

	self.worker.start()
1 Like

I would look into the threadpool for good examples

https://doc.qt.io/qt-5/thread-basics.html
https://doc.qt.io/qt-5/examples-threadandconcurrent.html

1 Like

There are a few key things to keep in mind when using threads.

  1. Python will not run code in parallel, but it will allow for concurrency. This basically means if you are doing something that is very CPU heavy, threading might not actually help you much.
  2. Maya requires that you process all commands on the main thread. So if you are using maya.cmds as part of your work, you’ll need to use either maya.utils.executeDeferred or maya.utils.executeInMainThreadWithResult.
  3. Qt also expects most GUI code to be run from the main thread, luckily slots/signals can be used to safely communicate across threads (this is pretty much the entire reason the slots/signals system exists)

When in doubt, refer to the documentation: Maya Help | Python and threading | Autodesk

2 Likes