Qt5 中 QSystemTrayIcon 类提供了系统托盘的功能
具体功能
- 初始化
初始化 QSystemTrayIcon 对象, 需要传递一个父控件作为初始参数
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QWidget
app = QApplication(sys.argv)
window = QWidget()
tray = QSystemTrayIcon(window)
# 系统托盘图标
tray.setIcon(QIcon('../image/Qt5.ico'))
# 鼠标悬停提示
tray.setToolTip('PyQt5')
tray.show()
QSystemTrayIcon 对象可以设置托盘图标以及鼠标悬停提示, 另外需要手动调用 tray.show()
, 其不会随父控件 window.show()
而自动展示
- 其中图标可以使用 Qt5 自带的图标
tray.setIcon(QApplication.style().standardIcon(0))
- 右键菜单
右键点击托盘图标时, 弹出右键菜单
# 创建托盘图标菜单
menu = QMenu(window)
# 添加菜单项
action_show = QAction('显示', window)
action_show.triggered.connect(window.show)
action_quit = QAction('退出', window)
action_quit.triggered.connect(app.quit)
menu.addAction(action_show)
menu.addAction(action_quit)
- 系统消息
QSystemTrayIcon.showMessage(title, msg, icon)
其中 icon 有以下几种类型:
- QSystemTrayIcon.NoIcon
- QSystemTrayIcon.Information
- QSystemTrayIcon.Warning
- QSystemTrayIcon.Critical
这些常量都属于类变量
QSystemTrayIcon 对象可以向系统的通知栏发送消息
tray.showMessage('提示', '右键单击', tray.Information)
- 鼠标互动
除了上面的右键菜单, QSystemTrayIcon 类还可通过 QSystemTrayIcon.activated
信号监测对托盘图标的单击, 双击, 按下鼠标中键, 具体类型有:
- QSystemTrayIcon.Context
- QSystemTrayIcon.DoubleClick
- QSystemTrayIcon.Trigger
- QSystemTrayIcon.MiddleClick
msg = {
QSystemTrayIcon.Trigger: '左键单击',
QSystemTrayIcon.Context: '右键单击',
QSystemTrayIcon.DoubleClick: '双击',
QSystemTrayIcon.MiddleClick: '鼠标中键'
}
def showMsg(reason):
tray.showMessage('提示', msg[reason], tray.Information)
tray.activated.connect(self.showMsg)
完整示例
"""
使用系统托盘
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (
QAction,
QApplication,
QMenu,
QSystemTrayIcon,
QWidget,
qApp
)
class Window(QWidget):
def __init__(self):
super().__init__()
self.resize(320, 240)
self.setWindowTitle('PyQt5 System Tray')
self.setWindowIcon(QIcon('../image/PyQt5.png'))
self.msg = {
QSystemTrayIcon.Trigger: '左键单击',
QSystemTrayIcon.Context: '右键单击',
QSystemTrayIcon.DoubleClick: '双击',
QSystemTrayIcon.MiddleClick: '鼠标中键'
}
self.initSystemTray()
def initSystemTray(self):
# 创建系统托盘图标对象
self.tray = QSystemTrayIcon(self)
self.tray.setIcon(QIcon('../image/Qt5.ico'))
# 鼠标悬停展示
self.tray.setToolTip('系统托盘')
# 创建托盘图标菜单
menu = QMenu()
# 添加菜单项
action_show = QAction('显示', self)
action_show.triggered.connect(self.showWindow)
action_quit = QAction('退出', self)
action_quit.triggered.connect(qApp.quit)
menu.addAction(action_show)
menu.addAction(action_quit)
# 将菜单设置到托盘图标
self.tray.setContextMenu(menu)
self.tray.activated.connect(self.showMsg)
self.tray.show()
def showWindow(self):
self.setWindowState(
self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive
)
def showMsg(self, reason):
self.tray.showMessage('提示', self.msg[reason], self.tray.Information)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())