PyQt 右下角提示(Toast Notification)示例

在 PyQt 中实现右下角的提示通知(通常称为 Toast Notification)是一个常见需求。这样的通知通常用于显示应用程序的状态更新或其他重要信息。

准备工作

确保你的环境中已经安装了 Python 和 PyQt5。

bash 复制代码
pip install PyQt5

示例代码

下面是一个简单的示例,展示如何使用 QSystemTrayIconQMessageBox 来实现右下角的提示通知。

python 复制代码
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction, QMessageBox
from PyQt5.QtGui import QIcon

def show_notification():
    tray.showMessage("Notification", "This is a sample notification!", QIcon("icon.png"), 2000)

app = QApplication([])

# 创建系统托盘图标
tray = QSystemTrayIcon(QIcon("icon.png"), parent=app)

# 创建右键菜单
menu = QMenu()
show_action = QAction("Show Notification")
show_action.triggered.connect(show_notification)
menu.addAction(show_action)
exit_action = QAction("Exit")
exit_action.triggered.connect(app.quit)
menu.addAction(exit_action)

tray.setContextMenu(menu)
tray.show()

# 显示一个初始通知
show_notification()

app.exec_()

代码解释

  • QSystemTrayIcon 是用于在系统托盘区域显示图标的类。
  • QMenuQAction 用于创建托盘图标的右键菜单。
  • show_notification 函数用于显示通知。它使用 QSystemTrayIconshowMessage 方法。

运行示例

保存上面的代码到一个文件(例如 tray_notification.py),并运行它。你应该会看到系统托盘区域有一个新的图标,右键点击它会显示一个菜单,其中有一个 "Show Notification" 选项。点击这个选项,你会看到一个右下角的提示通知。

这样,你就成功地使用 PyQt 实现了一个简单的右下角提示通知功能。你可以根据需要进一步定制这个功能。

相关推荐
程序员cxuan10 分钟前
DeepSeek 多模态深度实测,确实有东西的
人工智能·后端·程序员
evans在进步29 分钟前
Spring Boot 核心机制详解:自动装配、事件监听、异步任务与请求映射
java·spring boot·后端
程序员cxuan34 分钟前
一招让你的 Claude 被封了也能用
人工智能·后端·程序员
Zane199434 分钟前
HashSet、TreeSet、LinkedHashSet:底层都是"套壳"
java·后端
sigterM先生1 小时前
Ollama + Go 搭建 AI 告警分析管道
后端·ai编程
AI多Agent协作实战派1 小时前
AI多Agent协作系统实战(四十九):它说唤醒了agent,agent却还在睡觉
后端
用户7813667114451 小时前
对象存储(RGW)架构详解
后端
Python私教1 小时前
软件开发报价为什么能差 3 倍:需求范围、验收标准和变更成本怎么算
后端·python·架构
苏三说技术1 小时前
为什么越来越多人用gRPC?
后端
MacroZheng1 小时前
程序员看文档神器,装上它,看Spring官方文档就一目了然了!
java·人工智能·后端