QT实现最小化到Icon单击双击显示窗口
最近在学习用QT开发一个项目,参考了网上的例子完成了一个QT实现最小化到Icon单击双击显示窗口的例子,分享给大家,也感谢大家的网络分享。项目会放在www.pavogroup.top上面,大家可以参考一下。
在头文件里面定义bool isIconExist;以避免重复创建多个icon。
void HelpDeskClientDialog::changeEvent(QEvent *event)
{
if((event->type()==QEvent::WindowStateChange)&&isMinimized())
{
hide();
event->ignore();
//初始化两个项目
QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
QAction* showAction = new QAction(QStringLiteral("Display Window"));//项1
QAction* exitAction = new QAction(QStringLiteral("EXIT"));//项2
//项1的点击槽函数
connect(showAction, &QAction::triggered, this, [=]()
{
this->show();
});
//项2的点击槽函数
connect(exitAction, &QAction::triggered, this, [=]()
{
qDebug()<<"exit";
QApplication::exit(0);
});
connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
//初始化菜单并添加项
QMenu* trayMenu = new QMenu(this);//菜单
trayMenu->addAction(showAction);
trayMenu->addAction(exitAction );
//创建一个系统托盘
if(isIconExist == true)
{
return;
}
else
{
trayIcon->setIcon(QIcon(":/Icon/bird2.png")); //设置托盘图标
trayIcon->setContextMenu(trayMenu); //设置菜单
trayIcon->setToolTip ("Super HelpDesk");
trayIcon->show();
isIconExist = true;
}
}
}
void HelpDeskClientDialog::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::Trigger:
//单击托盘图标
this->showNormal();
break;
case QSystemTrayIcon::DoubleClick:
//双击托盘图标
//双击后显示主程序窗口
this->showNormal();
break;
default:
break;
}
}