Qt程序托盘逻辑指的是关闭软件(比如一些软件右上角的X)则隐藏软件到系统托盘,操作系统托盘或者软件内部的退出才是真正的退出,有几个点需要处理。
一.点击伪关闭按钮隐藏软件到托盘
实际上Qt只需要调用两个函数即可
void CloseWin()
{
showMinimized();
hide();
}
二.系统托盘
使用的的是Qt系统托盘类QSystemTrayIcon
QSystemTrayIcon* m_system_icon{nullptr}; //系统托盘中提供一个图标
处理以下几个函数:
1.初始化(连接一些槽函数)
void BFMainWin::InitSystemTrayIcon()
{
//托盘图标路径
QString strPath =XXXX;
QIcon* ico = new QIcon(strPath);
QSystemTrayIcon* p = new QSystemTrayIcon(*ico, this);
if (!p)
{
// Q_ASSERT( 0 );
}
else
{
//提示名字
p->setToolTip("XXXXX");
QMenu* m = new CTrayMenu /*new QMenu*/;
//样式表设置
m->setStyleSheet(
"QMenu {border-radius:3px;background-color:#FFFFFF;border:1px solid rgba(128,128,128,1);}\
QMenu::item {border-radius:2px;min-width:80px;font-size:12px;font-family:\"Microsoft YaHei\";color: rgb(0,0,0);background:#FFFFFF;border:1px solid #FFFFFF;padding:0px 10px;margin:0px 0px;}\
QMenu::item:selected {border-radius:2px;background:#1B90FB;border:1px solid #1B90FB;color: #FFFFFF;} \
QMenu::item:pressed {border-radius:2px;background:#1B90FB;border:1px solid #1B90FB;color: #FFFFFF;)}");
//菜单的槽函数
QAction* s = new QAction(QString::fromWCharArray(L"显示/隐藏"), this);
QAction* a = new QAction(QString::fromWCharArray(L"关于XXXX"), this);
QAction* e = new QAction(QString::fromWCharArray(L"退出"), this);
m->addAction(s);
m -> addAction(a);
m->addSeparator();
m->addAction(e);
connect(s, SIGNAL(triggered(bool)), this, SLOT(slotShowOrHide()));
connect(a, SIGNAL(triggered(bool)), this, SLOT(slotOnAbout()));
connect(e, SIGNAL(triggered(bool)), this, SLOT(slotOnExit()));
p->setContextMenu(m);
p->show();
m_system_icon = p;
//点击事件
connect(m_system_icon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(Slot_IconIsActived(QSystemTrayIcon::ActivationReason)));
}
}
2.隐藏/显示功能
void BFMainWin::slotShowOrHide()
{
//最小化的情况下,isVisible也是true
if (this->isVisible())
{
if (this->isMinimized())
{
//最小化情况下唤醒
this->raise();
this->showNormal();
this->activateWindow();
}
else
{
this->showMinimized();
this->hide();
}
} else {
this->raise();
this->showNormal();
this->activateWindow();
}
}
3.点击托盘图标
void BFMainWin::Slot_IconIsActived(QSystemTrayIcon::ActivationReason reason)
{
if (QSystemTrayIcon::Trigger == reason)
{
this->raise();
if (IsMaxState())
{
this->showMaximized();
}
else
{
this->showNormal();
}
this->activateWindow();
}
}