pyqt 自定义通知栏,右下角通知栏,仿系统托盘

自定义一个通知框

class MyMessageBox(QMessageBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.desktop=QDesktopWidget()
        self.setGeometry(self.desktop.availableGeometry().width()-400,self.desktop.availableGeometry().height()-180,400,150)
    def resizeEvent(self,event):
        self.setFixedSize(400,150)
    def showEvent(self,event):
        super().showEvent(event) 
        self.setFixedSize(400,150)

使用:


    def slot_autoclose_information(self,text,time = 4000):
        infoBox = MyMessageBox(self) ##Message Box that doesn't run
        infoBox.setIcon(QMessageBox.Information)
        infoBox.setText(text)
        infoBox.setWindowTitle("Information")
        infoBox.setStandardButtons(QMessageBox.Ok )
        infoBox.setWindowModality(Qt.NonModal)
        infoBox.setWindowFlags(Qt.Dialog  | Qt.WindowCloseButtonHint)
        if PythonVersion>3.4:
            infoBox.setTextInteractionFlags(Qt.TextSelectableByMouse) #文本可被选中
        if time != -1:
            infoBox.button(QMessageBox.Ok).animateClick(time) #4秒自动关闭
        infoBox.show()

PyQt5 能够通过 QSystemTrayIcon 类来创建一个任务图标,以方便用户随时控制应用程序。任务图标可以用于提醒用户有新消息、进入特定模式或临时关闭程序等。在此类应用程序中,“状态托盘图标”用于在系统通知区域中显示应用程序的状态。 要创建任务图标,我们首先要在代码中导入 QSystemTrayIcon 类。通常情况下,在主窗口中建立一个 QTimer 对象,通过 QTimer 定时器来检查新消息等,并显示在任务图标的 tooltip 信息中。 代码实现的方法如下: ```python from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu from PyQt5.QtCore import QTimer class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.setIcon(QIcon('icon.ico')) self.setToolTip('System Tray Icon Demo') menu = QMenu() action1 = menu.addAction("打开主窗口") action2 = menu.addAction("退出") self.activated.connect(self.onTrayIconActivated) self.setContextMenu(menu) def onTrayIconActivated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.parent().show() if __name__ == '__main__': app = QApplication([]) w = MainWindow() tray = SystemTrayIcon(w) timer = QTimer() timer.timeout.connect(tray.showMessage('提示', '你有新消息')) timer.start(5000) tray.show() app.exec_() ``` 在上面的代码中,我们首先定义了一个 SystemTrayIcon 类,然后在该类中初始化了 QIcon、QMenu、QAction 对象等。在 QMenu 中,我们定义了如何在任务图标上右键单击时弹出的菜单,并使用了 self.activated 信号来定义单击任务图标时的操作。在 onTrayIconActivated 方法中,我们可以根据 reason 参数来判断是怎么单击的,并执行不同的操作。最后,我们在 main 函数中使用 QTimer 定时器来检查新消息,并显示在任务图标的 tooltip 信息中。 在 PyQt5 中创建一个任务图标并不难,但是如何实现具体的用户交互体验以及利用任务图标进行实际功能呢,这就需要开发者自己进行设计和思考了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值