天天看點

Qt最小化到托盤、恢複并置頂

Qt最小化到托盤、恢複并置頂

在window.h檔案中添加如下内容:

//window.h

QSystemTrayIcon *trayicon;      
QMenu *trayiconMenu;      

//托盤點選處理槽函數

private slots:      
void onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason);      

在window.cpp檔案中添加如下内容,在構造函數中對添加的兩個變量進行初始化添加托盤圖示,連結槽函數,其中槽函數用于響應在托盤圖示及托盤菜單上的滑鼠點選操作:

//window.cpp

trayicon = new QSystemTrayIcon(this);      
connect(trayicon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason)));      
QIcon icon("MyICO.ico");      
trayicon->setIcon(icon);      
trayicon->show();      

//最小化處理

void Window::changeEvent(QEvent *e)      
{      
if((e->type()==QEvent::WindowStateChange)&&this->isMinimized())      
{      
this->hide();      
//        QTimer::singleShot(100, this, SLOT(close()));      
}      
}      

//實作槽函數

void BluetoothSMS::onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason)      
{      
switch(reason)      
{      
//單擊      
case QSystemTrayIcon::Trigger:      
//輕按兩下      
case QSystemTrayIcon::DoubleClick:      
if(this->isHidden())      
{      
//恢複視窗顯示      
this->show();      
//一下兩句缺一均不能有效将視窗置頂      
this->setWindowState(Qt::WindowActive);      
this->activateWindow();      
ui->MsgText->setFocus();      
}      
else      
{      
this->hide();      
}      
break;      
default:      
break;      
}      
}      

繼續閱讀