import threading import time from PyQt5.QtCore import QTimer, Qt from PyQt5.QtWidgets import * from queue import Queue class PopMessage: def __init__(self, parent): super().__init__() self.parent = parent desktop = QDesktopWidget() self.screenRect = desktop.availableGeometry() self.dialog = QDialog( flags=Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint | Qt.WindowStaysOnTopHint ) self.dialog.setGeometry(int(self.screenRect.width() * 0.4), 80, 500, 60) # 调整大小和位置 self.dialog.setStyleSheet( "background-color: none;" ) self.label = QLabel() self.label.setStyleSheet( "font: 24px \"Microsoft YaHei UI\";" "color: #409eff;" "border: none;" ) self.label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.icon_button = QPushButton("✕") self.icon_button.setStyleSheet( "border: none;" "font: 600 24px;" "background-color: none;" "color: #409eff;" ) self.icon_button.clicked.connect(self.close_message_action) self.message_layout = QHBoxLayout() self.message_layout.addWidget(self.label, 90) self.message_layout.addWidget(self.icon_button, 10) self.dialog.setLayout(self.message_layout) self.queue = Queue() # 消息队列 threading.Thread(target=self._show_from_queue, daemon=True).start() # 启动后台线程处理队列 def show(self, title_label): self.queue.put(title_label) # 将消息放入队列 def _show_from_queue(self): while True: title_label = self.queue.get() # 从队列获取消息 self.label.setText(title_label) self.dialog.show() time.sleep(5) # 5 秒后自动关闭 self.dialog.hide() def close_message_action(self): self.dialog.hide()