Search code examples
pythonpyqtpyqt5qthread

PyQt5.QThread's start() méthod don't execute the run() méthod


im starting to learn PyQt5 and Qthread and im trying to do a simple QThread implementation, i know it's obvious but i can't really get why it dosen't work

my code :

from PyQt5 import QtCore


class WorkingThread(QtCore.QThread):
    def __init__(self):
        super().__init__()

    def run(self):
        print(" work !")


class MainWindow(QtCore.QObject):

    worker_thread = WorkingThread()

    def engage(self):
        print("calling start")
        self.worker_thread.start()


if __name__ == "__main__":
    main = MainWindow()
    main.engage()

the output:

calling start

Process finished with exit code 0

no "work !" printed


Solution

  • many of the elements of Qt need an eventloop to work correctly, and that is the case of QThread, as in this case there is no GUI it is appropriate to create a QCoreApplication:

    from PyQt5 import QtCore
    
    
    class WorkingThread(QtCore.QThread):
        def run(self):
            print(" work !")
    
    
    class MainWindow(QtCore.QObject):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.worker_thread = WorkingThread()
    
        def engage(self):
            print("calling start")
            self.worker_thread.start()
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtCore.QCoreApplication(sys.argv)
        main = MainWindow()
        main.engage()
        sys.exit(app.exec_())