|
发表于 2024-3-17 11:50:24
|
显示全部楼层
如果每个按钮的耗时操作不同,我们可以针对每个按钮单独创建不同的工作线程。下面是一个示例代码,演示了如何为每个按钮创建独立的工作线程来处理耗时操作:
- from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
- from PySide6.QtCore import QThread, Signal
- class WorkerThread(QThread):
- finished = Signal() # 自定义信号,在线程完成后发送
- def __init__(self, button_id):
- super().__init__()
- self.button_id = button_id
- def run(self):
- # 根据按钮 ID 执行不同的耗时操作
- if self.button_id == 0:
- # 处理按钮1的耗时操作
- for i in range(5):
- print(f"Button 1 clicked, iteration {i+1}")
- self.sleep(1)
- elif self.button_id == 1:
- # 处理按钮2的耗时操作
- for i in range(3):
- print(f"Button 2 clicked, iteration {i+1}")
- self.sleep(1)
- # 添加其他按钮的耗时操作...
- self.finished.emit() # 发送信号表示线程完成
- class WindowB(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setup_ui()
- def setup_ui(self):
- self.setWindowTitle("Window B")
- self.buttons = []
- for i in range(6):
- button = QPushButton(f"Button {i+1}", self)
- button.clicked.connect(self.on_button_clicked)
- self.buttons.append(button)
- def on_button_clicked(self):
- button_id = self.buttons.index(self.sender())
- worker = WorkerThread(button_id) # 创建工作线程
- worker.finished.connect(self.on_worker_finished) # 绑定线程完成信号
- worker.start() # 启动工作线程
- def on_worker_finished(self):
- print("Worker finished")
- app = QApplication()
- window_b = WindowB()
- window_b.show()
- app.exec()
复制代码
在 `run` 方法中,根据按钮的 ID 来判断执行哪个按钮对应的耗时操作。你可以根据需要在每个 `if` 分支中编写不同的耗时操作代码。
通过这种方式,每个按钮都有自己独立的工作线程来处理耗时操作,并且不会相互影响。希望这可以满足你的需求。如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|