Search code examples
pythonpyqtpyqt5qthread

QThread can not be called in PyQt


I have implement a subclass about the QThread, but the run can not be called:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyThread(QThread):
    def __init__(self):
        super(MyThread,self).__init__()

    def run(self):
        for i in range(1000):
            print(i)
if __name__ == '__main__':
    import sys
    class MainWindow(QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.resize(500,500)
            self.label = QLabel()
            self.setCentralWidget(self.label)
            layout = QHBoxLayout()
            self.label.setLayout(layout)
            btn = QPushButton('start')
            layout.addWidget(btn)
            btn.clicked.connect(self.BTNClick)
        def BTNClick(self):
            thread = MyThread()
            thread.start()

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

When I debug the code, I find the MyThread is normally run. But when I directly run the code, the function 'run' would not be called.


Solution

  • A local variable is deleted when you finish executing the function, in your case thread is a local variable of BTNClick, so when you start it is eliminated, if you want the thread to persist even after executing BTNClick you must do it an attribute using self:

    def BTNClick(self):
        self.thread = MyThread()
        self.thread.start()