|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Created on 2021年12月09日 |
| 5 | +@author: Irony |
| 6 | +@site: https://pyqt.site , https://github.com/PyQt5 |
| 7 | + |
| 8 | +@file: TrayNotify |
| 9 | +@description: 托盘闪烁 |
| 10 | +""" |
| 11 | + |
| 12 | +try: |
| 13 | + from PyQt5.QtCore import QTimer |
| 14 | + from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QPushButton, |
| 15 | + QStyle, QSystemTrayIcon, QWidget) |
| 16 | +except ImportError: |
| 17 | + from PySide2.QtCore import QTimer |
| 18 | + from PySide2.QtWidgets import (QApplication, QHBoxLayout, QPushButton, |
| 19 | + QStyle, QSystemTrayIcon, QWidget) |
| 20 | + |
| 21 | + |
| 22 | +class Window(QWidget): |
| 23 | + |
| 24 | + def __init__(self, *args, **kwargs): |
| 25 | + super(Window, self).__init__(*args, **kwargs) |
| 26 | + layout = QHBoxLayout(self) |
| 27 | + layout.addWidget(QPushButton('开始闪烁', self, clicked=self.start_flash)) |
| 28 | + layout.addWidget(QPushButton('停止闪烁', self, clicked=self.stop_flash)) |
| 29 | + # 创建托盘图标 |
| 30 | + self.tray_icon = QSystemTrayIcon(self) |
| 31 | + self.tray_icon.setIcon(self.style().standardIcon( |
| 32 | + QStyle.SP_ComputerIcon)) |
| 33 | + self.tray_icon.show() |
| 34 | + # 图标闪烁定时器 |
| 35 | + self.tray_visible = True |
| 36 | + self.flash_timer = QTimer(self, timeout=self.flash_icon) |
| 37 | + |
| 38 | + def closeEvent(self, event): |
| 39 | + self.stop_flash() |
| 40 | + self.tray_icon.hide() |
| 41 | + super(Window, self).closeEvent(event) |
| 42 | + |
| 43 | + def start_flash(self): |
| 44 | + """开始闪烁""" |
| 45 | + if not self.flash_timer.isActive(): |
| 46 | + self.flash_timer.start(500) |
| 47 | + |
| 48 | + def stop_flash(self): |
| 49 | + """停止闪烁后需要显示图标""" |
| 50 | + if self.flash_timer.isActive(): |
| 51 | + self.flash_timer.stop() |
| 52 | + self.tray_icon.setIcon(self.style().standardIcon( |
| 53 | + QStyle.SP_ComputerIcon)) |
| 54 | + |
| 55 | + def flash_icon(self): |
| 56 | + """根据当前图标是否可见切换图标""" |
| 57 | + if self.tray_visible: |
| 58 | + self.tray_icon.setIcon(self.style().standardIcon( |
| 59 | + QStyle.SP_TrashIcon)) |
| 60 | + else: |
| 61 | + self.tray_icon.setIcon(self.style().standardIcon( |
| 62 | + QStyle.SP_ComputerIcon)) |
| 63 | + self.tray_visible = not self.tray_visible |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + import sys |
| 68 | + app = QApplication(sys.argv) |
| 69 | + w = Window() |
| 70 | + w.show() |
| 71 | + sys.exit(app.exec_()) |
0 commit comments