【Qt】在Win系统上的消息通知

[TOC]

需求描述: Qt应用程序在windows系统上发送win消息通知

演示

演示

代码

代码实现很简单,主要调用的接口为QSystemTrayIcon.showMessage()

使用的Demo为 【Qt】 鼠标 hover 操作时弹出文字气泡_欧恩意的博客-CSDN博客 这篇文章,结合图片隐藏显示,在系统显示通知。

widget.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QImage>
#include <QPixmap>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QIcon>
#include <QAction>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
Q_OBJECT

public:
Widget(QWidget *parent = nullptr);
~Widget();
public:
QSystemTrayIcon *trayIcon;
private slots:
void stTrayIconActive(QSystemTrayIcon::ActivationReason acReason);
void on_pushButton_clicked();

private:
Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);

QPixmap img(":/Win11.jpg");

ui->label->setPixmap(img);
ui->label->setScaledContents(true);
ui->label->setToolTip(QString("壁纸《Win11.png》"));
ui->pushButton->setToolTip(QString("隐藏或显示图片"));

QIcon icon = QApplication::style()->standardIcon((QStyle::StandardPixmap)0);
QIcon icon1 = QApplication::style()->standardIcon((QStyle::StandardPixmap)9);

//设置通知栏的图标
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(icon);

//设置通知栏的单击事件
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(stTrayIconActive(QSystemTrayIcon::ActivationReason)));

//设置通知栏的右键菜单
QMenu * menu = new QMenu();

//设置菜单项目
QAction *actionHide = new QAction(icon, "Hide", menu);

menu->addAction(actionHide);
trayIcon->setContextMenu(menu);
// 设置Action的响应
connect(actionHide, SIGNAL(triggered()), this, SLOT(stActionHide()));
trayIcon->show();

//托盘的消息提示
trayIcon->showMessage("title", "this is a message", icon1);
}

Widget::~Widget()
{
delete ui;
}

void Widget::stTrayIconActive(QSystemTrayIcon::ActivationReason acReason)
{
switch (acReason)
{
case QSystemTrayIcon::Trigger:
{
showNormal();
break;
}
default:
;
}
}

void Widget::on_pushButton_clicked()
{
QIcon icon = QApplication::style()->standardIcon((QStyle::StandardPixmap)0);
QIcon icon1 = QApplication::style()->standardIcon((QStyle::StandardPixmap)9);

if(ui->label->isVisible())
{
trayIcon->showMessage("提醒", "隐藏图片", icon1);
ui->label->hide();
}
else
{
trayIcon->showMessage("提醒", "显示图片", icon1);
ui->label->setVisible(true);
}
}

widget.ui

![UI](Qt Win消息通知/Qt Win消息通知2.png)


【Qt】在Win系统上的消息通知
https://hodlyounger.github.io/B_Code/Qt/【Qt】Win消息通知/
作者
mingming
发布于
2023年10月27日
许可协议