|
发表于 2024-3-14 22:20:03
|
显示全部楼层
如果在窗体B中的按钮调用了窗体A中的方法来处理耗时任务,那么将线程类定义在窗体A中是可行的。您可以在窗体B中通过信号与槽的方式通知窗体A启动线程,并在窗体A中处理线程的结果。以下是修改后的示例代码:from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel
from PySide6.QtCore import QThread, Signal
class MyThread(QThread):
operation_finished = Signal(dict)
def run(self):
# 在这里编写耗时的任务代码
# ...
# 任务完成后发射信号,并传递相应的参数
exclude_rules = {'1': exclude_rows, '2': exclude_cols}
self.operation_finished.emit(exclude_rules)
class BaseWindow(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.label = QLabel("进度条")
layout.addWidget(self.label)
self.setLayout(layout)
def on_operation_finished(self, exclude_rules):
# 在这里处理线程信号
print("操作完成:", exclude_rules)
# ...
class WindowA(BaseWindow):
def __init__(self):
super().__init__()
def start_thread(self):
# 创建线程对象
self.thread = MyThread()
# 连接信号和槽函数
self.thread.operation_finished.connect(self.on_operation_finished)
# 启动线程
self.thread.start()
class WindowB(BaseWindow):
def __init__(self):
super().__init__()
self.button = QPushButton("启动线程")
self.button.clicked.connect(self.start_thread)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def start_thread(self):
# 发射信号,通知窗体A启动线程
self.signal_start_thread.emit()
app = QApplication([])
window_a = WindowA()
window_b = WindowB()
window_b.signal_start_thread.connect(window_a.start_thread)
window_a.show()
window_b.show()
app.exec()在这个示例中,我们将线程类`MyThread`定义在了主窗口类`BaseWindow`的内部。窗体A(`WindowA`)继承自基本窗口类`BaseWindow`,并在其中定义了启动线程的方法`start_thread()`,在该方法中创建线程对象、连接信号和槽函数、启动线程。窗体B(`WindowB`)也继承自基本窗口类`BaseWindow`,并在其中添加了一个按钮用于触发启动线程的操作。当在窗体B中点击按钮时,通过信号`signal_start_thread`通知窗体A启动线程。窗体A响应该信号后调用`start_thread()`方法来启动线程,并在`on_operation_finished()`方法中处理线程的结果。希望以上修改能够满足您的需求。如果还有疑问,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|