![](/img/trans.png)
[英]PyQt QTimer problem QTimer can only be used with threads started with 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.