我创建了一个长时的工作类,并在主线程中实例化,然后再实例化一个QThread对象, 将工作对象加进去,最后起动线程,为什么还是会使主界面无响应呢?
工作类
class Worker(QObject):
progress_updated = pyqtSignal(int, str) # (进度百分比, 状态消息)
# result = pyqtSignal(str) # 结果信号
finished = pyqtSignal(bool, str) # 完成信号
def __init__(self, parent=None):
super().__init__(parent)
self._is_running = False
def cancel(self):
self._is_running = False
def do_cycles(self, con, groups: List[Group], total_seconds, total_cycles) -> None:
begin_time = int(time.time())
self._is_running = True
try:
# 开始总的循环
for c in range(total_cycles):
if not self._is_running:
break
# 开始group的遍历
for g in range(len(groups)):
if not self._is_running:
break
group = groups[g]
print(f"g={g}")
print(f"groupid:{group.id}")
# 开始对单个组内的命令执行循环
for s in range(group.cycles):
if not self._is_running:
break
# 遍历组内命令
for i in range(len(group.sequences)):
if not self._is_running:
break
seq = group.sequences[i]
# self.label_status.setText(f"当前执行第{c + 1}次循环, 第{g + 1}组的第{s + 1}次循环,当前第{i + 1}步。")
# self.label_status.update()
# self.label_status.repaint()
SwitchCommand.send_operation(con, seq.switch, seq.operation)
start_time = int(time.time())
time.sleep(1)
while int(time.time()) - start_time < seq.duration:
if not self._is_running:
break
progress = int(((int(time.time())-begin_time) / total_seconds) * 100)
status = f"当前执行第{c + 1}次循环, 第{g + 1}组的第{s + 1}次循环,当前第{i + 1}步。"
self.progress_updated.emit(progress, status)
time.sleep(1) # 每隔1s检查是否达到驻留时间值。
if self._is_running:
self.finished.emit(True, "程序运行结束!")
except Exception as e:
self.finished.emit(False, f"程序运行失败!{str(e)}")
finally:
self._is_running = False
主程序中实现类:
```python
"""初始化工作线程"""
self.thread = QThread()
self.worker = Worker()
self.worker.moveToThread(self.thread)
# 连接信号
self.worker.progress_updated.connect(self.update_progress)
# self.worker.result.connect(self.show_result)
self.worker.finished.connect(self.handle_task_completion)
self.thread.started.connect(lambda: self.worker.do_cycles(self.con, self.group_list, self.total_second, self.total_cycles))
按钮事件中开启线程:
self.thread.start()
```