一、展示效果

Qt--实现程序系统托盘_托盘图标

二、具体操作

widget.h

#ifndef
#define

#include <QWidget>
#include <QCommonStyle>
#include <QSystemTrayIcon>
#include <QAction>
#include <QMenu>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
Q_OBJECT

public:
Widget(QWidget *parent = nullptr);
~Widget();

QSystemTrayIcon *trayIcon;
QAction *minimizeAction;
QAction *restoreAction;
QAction *quitAction;
QMenu *trayIconMenu;

private slots:
void trayiconActivated(QSystemTrayIcon::ActivationReason reason);

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

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);

//创建托盘图标
QIcon icon = QIcon(":images/logo.png");
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(icon);
trayIcon->setToolTip(tr("速度仪"));
QString titlec=tr("速度仪");
QString textc=tr("速度仪:给你丝滑版的享受");
trayIcon->show();

//弹出气泡提示
trayIcon->showMessage(titlec,textc,QSystemTrayIcon::Information,5000);

//添加单/双击鼠标相应
connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this,SLOT(trayiconActivated(QSystemTrayIcon::ActivationReason)));

//创建监听行为
minimizeAction = new QAction(tr("最小化 (&I)"), this);
connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
restoreAction = new QAction(tr("还原 (&R)"), this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAction = new QAction(tr("退出 (&Q)"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

//创建右键弹出菜单
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon->setContextMenu(trayIconMenu);
}

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

void Widget::trayiconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Trigger:
//单击托盘图标
case QSystemTrayIcon::DoubleClick:
//双击托盘图标
this->showNormal();
this->raise();
break;
default:
break;
}
}