实现功能:1.关闭窗口时,不退出,而是隐藏在系统托盘。2.系统托盘图标单击或双击显示窗口,右键退出。
头文件:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSystemTrayIcon>
#include <QtGui>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QSystemTrayIcon *m_SystemIcon; //系统托盘图标
void closeEvent(QCloseEvent *event);
private slots:
void OnExitActionTriggered();
void SystemTrayClicked(QSystemTrayIcon::ActivationReason reason);
};
#endif // MAINWINDOW_H
源文件:
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_SystemIcon = new QSystemTrayIcon;
m_SystemIcon->setToolTip("显示图标");//设置文字
//设置托盘图标
m_SystemIcon->setIcon(QIcon("D:/QT_Library/SystemTrayIcon/icon/music.png"));
//设置托盘菜单
QMenu *menu = new QMenu;
menu->addAction(ui->actionTest1);
menu->addAction(ui->actionTest2);
menu->addSeparator(); //添加分割线
menu->addAction(ui->actionExit);
m_SystemIcon->setContextMenu(menu);
m_SystemIcon->show();
//关联到托盘:退出程序
connect(ui->actionExit,SIGNAL(triggered()),
this,SLOT(OnExitActionTriggered()));
//关联托盘,单击或双击显示主窗口
connect(m_SystemIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this,
SLOT(SystemTrayClicked(QSystemTrayIcon::ActivationReason)));
}
MainWindow::~MainWindow()
{
delete m_SystemIcon;
delete ui;
}
//点关闭窗口时,隐藏到托盘
void MainWindow::closeEvent(QCloseEvent *event)
{
this->hide();
event->ignore();
}
void MainWindow::OnExitActionTriggered()
{
QApplication::exit(0);
}
//单击或双击托盘图标显示主窗口
void MainWindow::SystemTrayClicked(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger ||
reason == QSystemTrayIcon::DoubleClick)
{
//正常显示
this->showNormal();
}
}
设计界面:(在设计界面添加的Action)