我已经实现了关于QThread的子类,但是无法调用run:
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'。
答案 0 :(得分:1)
当你完成执行函数时删除局部变量,在你的情况下,线程是BTNClick
的局部变量,所以如果你希望线程在执行{{{{ 1}}你必须使用BTNClick
:
self