pythonmultithreadingpyqt5qthread

Target a function with QThread


I'm aware of this structure

class MyThread(QThread):
    def __init__(self):
        super().__init__()
    
    def run():
       # do stuff

t = MyThread()
t.start()

With regular threading.Thread you can do something like this:

def stuff():
    # do stuff

t = threading.Thread(target=stuff)
t.start()

Any way to do this in pyqt5 with QThreads? Something like this:

t = Qthread(target=stuff)
t.start()

I tried that but I got this error:

TypeError: 'target' is an unknown keyword argument

Solution

  • You can add the function to a custom argument in the __init__, create an instance attribute for its reference and then run it in the run.

    class MyThread(QThread):
        def __init__(self, target=None):
            super().__init__()
            self.target = target
        
        def run(self):
            if self.target:
                self.target()
    
    def stuff():
        # do something
    
    t = MyThread(target=stuff)
    t.start()
    
    

    Be aware that access to UI elements is not allowed in external threads, so don't use the threaded function to do anything related to UI: reading values and properties is unreliable, and writing can cause your program to crash.