Qt托盘程序

使用QSystemTrayIcon类可以实现托盘程序。在这里使用QMainWindow做实例:

mainwindow.h头文件

 1 #ifndef MAINWINDOW_H
 2 #define MAINWINDOW_H
 3 
 4 #include 
 5 #include 
 6 #include 
 7 #include 
 8 #include 
 9 
10 namespace Ui {
11 class MainWindow;
12 }
13 
14 class MainWindow : public QMainWindow
15 {
16     Q_OBJECT
17 public:
18     explicit MainWindow(QWidget *parent = 0);
19     ~MainWindow();
20 
21 private:
22     void closeEvent(QCloseEvent * event);
23 
24 private:
25     Ui::MainWindow *ui;
26 
27     QSystemTrayIcon* systemIcon; //系统托盘
28     QAction* min; //最小化
29     QAction* max; //最大化
30     QAction* restore; //还原程序
31     QAction* quit; //退出程序
32     QMenu*   menu; //托盘程序的右键目录
33 };
34 
35 #endif // MAINWINDOW_H

mainwindow.cpp 源文件

 1 #include 
 2 #include "mainwindow.h"
 3 #include "ui_mainwindow.h"
 4 
 5 MainWindow::MainWindow(QWidget *parent) :
 6     QMainWindow(parent),
 7     ui(new Ui::MainWindow)
 8 {
 9     ui->setupUi(this);
10 
11     QIcon icon(":/new/prefix1/images/icon.ico");
12     systemIcon = new QSystemTrayIcon(this); //托盘程序
13     systemIcon->setIcon(icon);
14     systemIcon->setToolTip(QString::fromLocal8Bit("测试托盘程序"));
15 
16     //连接托盘菜单功能到槽函数
17     min = new QAction(QString::fromLocal8Bit("最小化窗口"), this);
18     connect(min, SIGNAL(triggered()), this, SLOT(hide()));
19     max = new QAction(QString::fromLocal8Bit("最大化窗口"), this);
20     connect(max, SIGNAL(triggered()), this, SLOT(showMaximized()));
21     restore = new QAction(QString::fromLocal8Bit("还原窗口"), this);
22     connect(restore, SIGNAL(triggered()), this, SLOT(showNormal()));
23     quit = new QAction(QString::fromLocal8Bit("退出"), this);
24     connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
25 
26     menu = new QMenu(this);
27     menu->addAction(min);
28     menu->addAction(max);
29     menu->addAction(restore);
30     menu->addSeparator();
31     menu->addAction(quit);
32     systemIcon->setContextMenu(menu);  //设置托盘程序功能菜单
33     systemIcon->show();
34 }
35 
36 MainWindow::~MainWindow()
37 {
38     delete ui;
39 }
40 
41 void MainWindow::closeEvent(QCloseEvent *event)
42 {
43     if(systemIcon->isVisible())
44     {
45         hide(); //隐藏主程序
46         systemIcon->showMessage(QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("测试程序正在后台运行!"));
47         event->ignore();
48     }
49 }

 

转载于:https://www.cnblogs.com/tyche116/p/8682943.html

你可能感兴趣的:(Qt托盘程序)