【问题标题】:QThread can not be called in PyQt在 PyQt 中不能调用 QThread
【发布时间】:2018-04-28 23:59:32
【问题描述】:

我已经实现了一个关于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'不会被调用。

【问题讨论】:

    标签: python pyqt pyqt5 qthread


    【解决方案1】:

    当你完成函数执行时,一个局部变量被删除,在你的情况下线程是一个局部变量BTNClick,所以当你启动它时它被消除了,如果你希望线程在执行BTNClick之后仍然存在,你必须使用self 来做一个属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2021-12-17
      • 2015-09-08
      • 2014-03-25
      • 2014-09-05
      • 1970-01-01
      相关资源
      最近更新 更多