简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM