QThread的子线程还在运行但是线程就被销毁了,导致程序闪崩,该错误是笔者用终端执行py文件时提示的。
再次调用self.thread_detec_l()之前添加两行:
self.thread_detec_l = ObjectDetection()
self.thread_detec_l.quit()
self.thread_detec_l.wait()
self.thread_detec_l.start()
def ObjectDetection_tf2(self)
self.thread_detec_l = ObjectDetection()
self.thread_detec_l.finished.connect(self.thread_detec_l.deleteLater)
self.thread_detec_l.start()
def ObjectDetection_tf2(self)
thread_detec_l = ObjectDetection()
self.task_list.append(thread_detec_l)
thread_detec_l.finished.connect(self.remove_thread)
thread_detec_l.start()
def remove_thread(self):
sender = self.sender()
if sender in self.task_list:
try:
self.task_list.remove(sender)
except Exception as e:
print(e)
笔者的具体情况:在主线程同时调用三个子线程进行后台的运算,在程序运行短暂时间就出现了如上错误。笔者的解决方法如下:
def ObjectDetection_tf2(self): # 开始处理
if self.dir_path=='': # 为左图所在的路径
self.StateInfo.setText('请选择要进行检测的图像路径!')
return
if self.T==0:
self.StateInfo.setText('请设置阈值!')
return
self.thread_detec_l = ObjectDetection(0,self.T,self.dir_path,self.tf2result_path) # 子线程一
self.task_list.append(self.thread_detec_l)
self.thread_detec_l.finished.connect(self.remove_thread)
self.thread_detec_l.results_img.connect(self.Hub_ResultsDisplay)
self.thread_detec_l.report_info.connect(self.Hub_Reportinfo)
self.thread_detec_l.process.connect(self.StateInfo.setText) # 显示识别进度
self.thread_detec_l.quit()
self.thread_detec_l.wait()
self.thread_detec_l.start()
self.thread_detec_r = ObjectDetection(1,self.T,self.dir_path.replace('_L','_R'),self.tf2result_path) # 子线程二
self.task_list.append(self.thread_detec_r)
self.thread_detec_r.finished.connect(self.remove_thread)
self.thread_detec_r.results_img.connect(self.Hub_ResultsDisplay)
self.thread_detec_r.report_info.connect(self.Hub_Reportinfo)
self.thread_detec_r.quit()
self.thread_detec_r.wait()
self.thread_detec_r.start()
def Reportinfo(self,Hub_reportinfo_l,Hub_reportinfo_r): # 中转站识别报告信息左右合并
self.dict_l = Hub_reportinfo_l[self.index_reportinfo]
self.dict_r = Hub_reportinfo_r[self.index_reportinfo]
for img_name,report_dict in self.dict_l.items(): # 字典只有一组元素也得用for来分离键和值
print(img_name,report_dict)
if img_name in self.dict_r:
self.dict_l[img_name].update(self.dict_r[img_name]) # 以{'K239+001-00000001':{(y1,x1,y2,x2):'Hengfeng',.....}}
self.thread_perimg_count = Perimg_Count(self.dict_l) # 子线程三
self.task_list.append(self.thread_perimg_count)
self.thread_perimg_count.finished.connect(self.remove_thread)
self.thread_perimg_count.excel_info.connect(self.InfoExcel) # 写入明细栏
self.thread_perimg_count.quit()
self.thread_perimg_count.wait()
self.thread_perimg_count.start()
self.index_reportinfo += 1
# self.thread_perimg_count.exec()
def remove_thread(self):
sender = self.sender()
if sender in self.task_list:
try:
self.task_list.remove(sender)
except Exception as e:
print(e)
笔者结合三种方法,成功实现了三个子线程同时运行,而不出现某个子线程中途被销毁的情况。