闪烁其实是两张图片来回切换,其中一张透明的图片。
from PySide6.QtWidgets import QApplication, QMainWindow, QSystemTrayIcon, QMenu, QMessageBox
from PySide6.QtCore import QTimer
from PySide6.QtGui import QIcon
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.initTrayIcon()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('Tray Icon Flashing Example')
def initTrayIcon(self):
self.trayIcon = QSystemTrayIcon(self)
self.originalIcon = QIcon('D:/data/10.jpg')
self.trayIcon.setIcon(self.originalIcon)
self.trayIcon.setVisible(True)
self.contextMenu = QMenu()
self.contextMenu.addSeparator()
self.showAction = self.contextMenu.addAction('显示')
self.exitAction = self.contextMenu.addAction('退出')
self.trayIcon.setContextMenu(self.contextMenu)
self.showAction.triggered.connect(self.showNormal)
self.exitAction.triggered.connect(QApplication.instance().quit)
# 定时器用于控制图标闪烁
self.flashTimer = QTimer(self)
self.flashTimer.timeout.connect(self.flashIcon)
self.flashTimer.setInterval(800) # 闪烁间隔时间
def startFlashing(self):
# 开始闪烁图标
self.flashingIcon = QIcon('D:/data/11.jpg')
self.trayIcon.setIcon(self.flashingIcon)
self.flashTimer.start()
def stopFlashing(self):
# 停止闪烁图标
self.trayIcon.setIcon(self.originalIcon)
self.flashTimer.stop()
def flashIcon(self):
# 切换图标以创建闪烁效果
print(self.trayIcon.icon())
if self.trayIcon.icon().cacheKey() == self.flashingIcon.cacheKey():
self.trayIcon.setIcon(self.originalIcon)
else:
self.trayIcon.setIcon(self.flashingIcon)
def showMessage(self):
# 显示托盘消息提示
# self.trayIcon.showMessage(
# 'New Message',
# 'You have received a new message!',
# QSystemTrayIcon.Information,
# 5000 # 显示持续时间,毫秒
# )
# 接收到消息后开始闪烁
self.startFlashing()
# 5秒后停止闪烁
QTimer.singleShot(50000, self.stopFlashing)
# 创建应用程序实例和主窗口
app = QApplication([])
window = MainWindow()
window.show()
window.showMessage()
app.exec_()