设计实现qt界面最小化到托盘,调试结果正常,直接点击exe文件运行程序正常运行,最小化后进入后台但是托盘没有出现图标
这是.h
#include <QMainWindow>
#include <QPushButton>
#include <QSystemTrayIcon>
#include <QHideEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void hideEvent(QHideEvent *event);
private:
Ui::MainWindow *ui;
QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu;
//窗口管理动作
QAction *minimizeAction;
QAction *maximizeAction;
QAction *restoreAction;
QAction *quitAction;
private slots:
void iconActivated(QSystemTrayIcon::ActivationReason reason);
};
这是.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//托盘初始化
QIcon icon = QIcon("icon.png");
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(icon);
trayIcon->setToolTip("a trayicon example");
trayIcon->show(); //必须调用,否则托盘图标不显示
//创建菜单项动作(以下动作只对windows有效)
minimizeAction = new QAction("最小化~", this);
connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); //绑定信号槽
maximizeAction = new QAction("最大化~", this);
connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
restoreAction = new QAction("还原~", this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAction = new QAction("退出~", this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); //关闭应用,qApp对应的是程序全局唯一指针
//创建托盘菜单(必须先创建动作,后添加菜单项,还可以加入菜单项图标美化)
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(maximizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this,SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Trigger:
trayIcon->showMessage("title","你单击了"); //后面两个默认参数
break;
case QSystemTrayIcon::DoubleClick:
trayIcon->showMessage("title","你双击了");
break;
case QSystemTrayIcon::MiddleClick:
trayIcon->showMessage("title","你中键了");
break;
default:
break;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::hideEvent(QHideEvent *event)
{
if(trayIcon->isVisible())
{
hide(); //隐藏窗口
trayIcon->showMessage("title","隐藏到托盘图标了"); //提示用户隐藏到了托盘
event->ignore(); //忽略事件
}
}