前言:
博主最近在做一個聊天軟件,雖然技術不咋滴,但遇到點干貨肯定是要跟大家分享的啦。下面就給大家分享一個qt實現程序隱藏才系統托盤的技巧。
裝備:
系統:linux,
qt版本:5.9.2,GCC:4.9.3.
1.頭文件聲明:
QSystemTrayIcon *mSysTrayIcon; //記得頭文件
void on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason);//槽函數的聲明
2.窗口初始化時創建托盤對象:
//新建QSystemTrayIcon對象
mSysTrayIcon = new QSystemTrayIcon(this);
//新建托盤要顯示的icon
QIcon icon = QIcon(":/new/images/im_icon.png");
//將icon設到QSystemTrayIcon對象中
mSysTrayIcon->setIcon(icon);
//當鼠標移動到托盤上的圖標時,會顯示此處設置的內容
mSysTrayIcon->setToolTip(QObject::trUtf8("xxx客戶端"));
//給QSystemTrayIcon添加槽函數
connect(mSysTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
//在系統托盤顯示此對象
mSysTrayIcon->show();
3.槽函數實現點擊事件。
//系統托盤功能
void ocswk::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch(reason){
case QSystemTrayIcon::Trigger:
//單擊托盤圖標,顯示窗體
this->show();
break;
case QSystemTrayIcon::DoubleClick:
//雙擊托盤圖標
//雙擊后顯示主程序窗口
QMessageBox::information(this,"xxx", "xxxxxx");
break;
default://還有個右鍵事件沒寫。
break;
}
}
4.體現圖標作用:決定是否退出程序或縮小圖標
// closeEvents
void ocswk::closeEvent(QCloseEvent *event)
{
QMessageBox button(QMessageBox::Warning, QString(tr("退出程序")),QString(tr("確認退出程序!")));
button.setStandardButtons (QMessageBox::Yes|QMessageBox::No);
button.setSizeIncrement(250,120);
button.setButtonText (QMessageBox::Yes,QString("確定退出"));
button.setButtonText (QMessageBox::No,QString("縮小托盤"));
if(button.exec() != QMessageBox::Yes)
{
this->hide();
event->ignore();
}else{
event->accept();
}
}
5.圖標抖動:來消息圖標抖動事件還沒完成(其實俺也不會啊),等后續更新吧。