Title Loading...
- Time Loading...
- Wordcount Loading...
Catalogue
记录PyQt中多线程操作报错:QThread: Destroyed while thread is still running 及其解决办法
今天在用PyQt给一个小工具写界面的时候,控制台抛出了这个错误:
QThread: Destroyed while thread is still running
翻译过来就是大意就是:在线程还在运行时就被破坏了。
下面贴上关键代码:
线程类
class InThread(QtCore.QThread):
_signal = QtCore.pyqtSignal(list)
def __init__(self, file_dir, wb):
super(InThread,self).__init__()
#...
def run(self):
#...
self._signal.emit(req)
调用
def inDo(self):
#...
inthread = InThread(self.file_dir, self.wb)
inthread._signal.connect(self.inCallback)
inthread.start()
几经调试,发现问题出在对线程类实例化即调用的过程中。博主自己的理解是,从上面的代码可以看出,我在实例化线程类InThread的时候,将其实例化为了局部数据成员,因此只在函数作用域内有效,当作用域内的所有代码自顶向下按顺序执行后,实例化的inthread线程类对象便被销毁了,而此时在类作用域之内的子线程仍在执行,因此会抛出这个错误。
最后的解决办法是,将线程对象实例化为类作用域的成员变量,代码如下:
def inDo(self):
#...
self.inthread = InThread(self.file_dir, self.wb)
self.inthread._signal.connect(self.inCallback)
self.inthread.start()