测试完成代码
This commit is contained in:
51
test.py
Normal file
51
test.py
Normal file
@ -0,0 +1,51 @@
|
||||
from PySide6.QtCore import QThread, Signal, Slot
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QLabel, QVBoxLayout, QPushButton
|
||||
import sys
|
||||
import time
|
||||
|
||||
# 定义子线程类
|
||||
class WorkerThread(QThread):
|
||||
# 创建信号,子线程处理完成后通知主线程弹窗
|
||||
show_dialog_signal = Signal(str)
|
||||
|
||||
def run(self):
|
||||
# 模拟子线程的工作
|
||||
time.sleep(3) # 假设任务执行需要 3 秒钟
|
||||
self.show_dialog_signal.emit("任务完成,弹出对话框") # 发出信号,通知主线程弹窗
|
||||
print("子线程")
|
||||
|
||||
# 定义主窗口类
|
||||
class MainWindow(QDialog):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setWindowTitle("主窗口")
|
||||
self.setGeometry(100, 100, 300, 200)
|
||||
|
||||
self.button = QPushButton("开始任务", self)
|
||||
self.button.clicked.connect(self.start_task)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(self.button)
|
||||
|
||||
@Slot(str)
|
||||
def show_dialog(self, message):
|
||||
# 接收到信号后显示弹窗
|
||||
dialog = QDialog(self)
|
||||
dialog.setWindowTitle("子线程通知")
|
||||
label = QLabel(message, dialog)
|
||||
dialog_layout = QVBoxLayout(dialog)
|
||||
dialog_layout.addWidget(label)
|
||||
dialog.exec()
|
||||
|
||||
def start_task(self):
|
||||
# 创建并启动子线程
|
||||
self.thread = WorkerThread()
|
||||
self.thread.show_dialog_signal.connect(self.show_dialog) # 连接信号到主线程的槽函数
|
||||
self.thread.start()
|
||||
|
||||
# 创建应用程序
|
||||
app = QApplication(sys.argv)
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
|
||||
sys.exit(app.exec())
|
||||
Reference in New Issue
Block a user