1 实现
1.1 .h文件中,声明变量和方法
//窗口任务栏属性
QSystemTrayIcon *trayIcon;
QMenu *trayMenu ;
void iconActivated(QSystemTrayIcon::ActivationReason);
QAction *trayShowMainAction;//托盘显示窗口信号发生体
QAction *trayExitAppAction;//托盘显示窗口信号发生体
void on_showMainAction();//托盘槽
void on_exitAppAction();//托盘槽
1.2 初始化托盘:
void initTray()
{
//创建托盘
this->initTrayIcon();
connect(trayIcon, &QSystemTrayIcon::activated,
this, &UIMainWindows::iconActivated);
//托盘事件
//显示界面
connect(trayShowMainAction, &QAction::triggered,
this, &UIMainWindows::showNormal);
//退出程序
connect(trayExitAppAction, &QAction::triggered,
this, &UIMainWindows::on_exitAppAction);
//this->setWindowState((this->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
//设置窗口样式
this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
}
1.3 创建托盘
void initTrayIcon()
{
//判断系统是否支持托盘图标显示
if(!QSystemTrayIcon::isSystemTrayAvailable())
{
//qDebug() <<"test";
return;
}
//实例化托盘图标控件
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon(":/image/main_menu.png")); //设置托盘图标显示
trayIcon->setToolTip("Calculator"); //显示提示信息
//创建托盘菜单
trayShowMainAction = new QAction(tr("显示主界面"),this);
trayExitAppAction = new QAction(tr("退出"),this);
trayMenu = new QMenu(this);
trayMenu ->addAction(trayShowMainAction);//添加事件
trayMenu ->addSeparator();//添加分割线
trayMenu ->addAction(trayExitAppAction);
trayIcon->setContextMenu(trayMenu );//托盘添加菜单
}
1.4 点击事件
void iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Trigger:
//trayIcon->showMessage("title","你单击了"); //后面两个默认参数
trayIcon->showMessage(tr("游戏平台"),
tr("欢迎使用此程序!"),
QSystemTrayIcon::Information,
700);
break;
case QSystemTrayIcon::DoubleClick:
//trayIcon->showMessage("title","你双击了");
//setVisible(true);
this->show();
break;
// case QSystemTrayIcon::MiddleClick://鼠标中间滚轮
// trayIcon->showMessage("title","你中键了");
// break;
default:
break;
}
}
void on_exitAppAction()
{
exit(0);
}