当前项目需要实现输出测试报告功能,通过按键的点击信号连接的槽,调用工程中文件输出类的全局变量中的方法,创建继承自QThread类的自定义类实现。
报错原因:原先的写法并没有将文件输出类中的exportThread变量定义为类变量,而是定义在方法中。当方法被返回(return)后,exportThread变量超出其作用域并被销毁。如果此时线程仍在运行,就会出现 QThread: Destroyed while thread is still running
的错误。
修改后代码如下:
按键定义:
def ButtonInit(self):
self.btExport = QPushButton('Export')
self.btExport.setFixedWidth(100)
self.btExport.clicked.connect(self.ExportClicked)
self.hBoxLayout.addWidget(self.btExport)
按键点击信号的槽:
def ExportClicked(self)
self.btExport.setEnabled(False)
global.exportObject.Export(self)
按键使能方法:
def BTExportEnable(self):
self.btExport.setEnabled(True)
文件输出类:
class Export():
def __init__(self):
self.exportThread = None
def Export(self, exportDialog):
self.exportThread = ExportThread()
self.exportThread.finished.connect(self.ExportThreadComplete)
self.exportThread.start()
测试数据输出报告线程类:
class ExportThread(QThread):
buttonSignal = pyqtSignal()
def __init__(self,parent=None):
super(ExportThread, self).__init__()
def run(self):
self.buttonSignal.emit()