PyQt中无法调用QThread

QThread can not be called in PyQt

我已经实现了一个关于QThread的子类,但是运行无法调用:

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_()

调试代码的时候发现MyThread正常是运行。但是当我直接运行代码时,函数'run'不会被调用。

一个局部变量在你执行完函数的时候被删除,你的线程是BTNClick的一个局部变量,所以当你启动的时候就被删除了,如果你希望线程执行完后仍然存在BTNClick 你必须使用 self:

做一个属性
def BTNClick(self):
    self.thread = MyThread()
    self.thread.start()