测试完成代码
This commit is contained in:
54
test2.py
Normal file
54
test2.py
Normal file
@ -0,0 +1,54 @@
|
||||
import threading
|
||||
|
||||
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
|
||||
from PySide6.QtCore import QThread, Signal, QObject
|
||||
|
||||
class Worker:
|
||||
# 定义一个类属性的信号
|
||||
|
||||
def __init__(self):
|
||||
self.task_done_signal = Signal(str)
|
||||
def run_task(self):
|
||||
import time
|
||||
time.sleep(2) # 模拟耗时操作
|
||||
# 发送信号
|
||||
self.task_done_signal.emit("子线程任务完成!")
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setWindowTitle("子线程信号示例")
|
||||
self.setGeometry(200, 200, 400, 300)
|
||||
|
||||
# 添加按钮
|
||||
self.button = QPushButton("启动子线程", self)
|
||||
self.button.setGeometry(100, 100, 200, 50)
|
||||
self.button.clicked.connect(self.run_task)
|
||||
|
||||
# 创建子线程和工作者对象
|
||||
self.worker_thread = threading.Thread(target=self.run_task)
|
||||
self.worker = Worker()
|
||||
|
||||
# 连接信号和槽
|
||||
self.worker.task_done_signal.connect(self.show_message)
|
||||
|
||||
def run_task(self):
|
||||
# 启动子线程
|
||||
self.worker_thread.start()
|
||||
|
||||
def show_message(self, message):
|
||||
# 显示来自子线程的消息
|
||||
QMessageBox.information(self, "任务完成", message)
|
||||
|
||||
# 停止子线程
|
||||
self.worker_thread.quit()
|
||||
self.worker_thread.wait()
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
|
||||
app.exec()
|
||||
Reference in New Issue
Block a user