参考:
代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSystemTrayIcon>
#include <QDebug>
#include <QMenu>
#include <QCloseEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void showWindow();
void on_exitAppAction();
void iconActivated(QSystemTrayIcon::ActivationReason reason);
protected:
void closeEvent(QCloseEvent *event);
private:
Ui::Widget *ui;
QSystemTrayIcon *sysTray;
//打开工具
//安全退出
QAction *open;
QAction *exit;
QMenu *contextMenu;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
sysTray=new QSystemTrayIcon(this);
sysTray->setIcon(QIcon(QApplication::applicationDirPath()+"/icon.ico"));
//qDebug()<<QApplication::applicationDirPath()+"/icon.ico";
open=new QAction("打开工具",this);
exit=new QAction("安全退出",this);
connect(open,&QAction::triggered,this,&Widget::showWindow);
connect(exit,&QAction::triggered,this,&Widget::on_exitAppAction);
connect(sysTray,&QSystemTrayIcon::activated,this,&Widget::iconActivated);
contextMenu=new QMenu(this);
contextMenu->addAction(open);
contextMenu->addAction(exit);
sysTray->setContextMenu(contextMenu);
sysTray->show();
this->hide();
}
Widget::~Widget()
{
delete ui;
}
void Widget::showWindow()
{
show();
raise();
}
void Widget::on_exitAppAction()
{
qApp->exit();
}
void Widget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
showWindow();
break;
default:
break;
}
}
void Widget::closeEvent(QCloseEvent *event)
{
this->hide();
event->ignore();
}
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}