更新:2022年6月23日
from PyQt5 import QtGui
from PyQt5.QtWidgets import QSystemTrayIcon
class MyTray(QSystemTrayIcon):
def __init__(self,window):
super().__init__()
try:
self.setIcon(QtGui.QIcon('icon/cpml.ico'))
self.activated.connect(self.iconClicked)
self.parent_window = window
self.bind(window)
except Exception as e:
print('systemtrayicon error :0',e)
def bind(self,window):
self.parent_window=window
def iconClicked(self,reason):
#鼠标点击icon传递的信号会带有一个整形的值,1是表示单击右键,2是双击,3是单击左键,4是用鼠标中键点击"
print('click')
if reason == 2 :#2是双击
try:
self.parent_window.show()
except Exception as e:
print(e)
加一段添加二级菜单的功能,暂未试验过
def showMenu(self):
"设计托盘的菜单,这里我实现了一个二级菜单"
self.menu = QMenu()
self.menu1 = QMenu()
self.showAction1 = QAction("显示消息1", self, triggered=self.showM)
self.showAction2 = QAction("显示消息2", self,triggered=self.showM)
self.quitAction = QAction("退出", self, triggered=self.quit)
self.menu1.addAction(self.showAction1)
self.menu1.addAction(self.showAction2)
self.menu.addMenu(self.menu1, )
self.menu.addAction(self.showAction1)
self.menu.addAction(self.showAction2)
self.menu.addAction(self.quitAction)
self.menu1.setTitle("二级菜单")
self.setContextMenu(self.menu)