目錄
前言:
1.先看效果圖
2.大致思路以及實(shí)現(xiàn)流程
3.具體代碼以及解釋
4.總結(jié)
前言:
使用QT開發(fā)桌面軟件,將軟件最小化至托盤這樣的功能的是比較常見的,今天自己實(shí)現(xiàn)一下這個(gè)功能,并進(jìn)行記錄總結(jié)。
1.先看效果圖
?主要功能就是當(dāng)軟件開始運(yùn)行,在系統(tǒng)托盤會(huì)自動(dòng)出現(xiàn)一個(gè)關(guān)于本軟件的系統(tǒng)托盤的圖標(biāo),你右擊這個(gè)圖標(biāo),可以彈出一個(gè)菜單欄,這樣的效果
2.大致思路以及實(shí)現(xiàn)流程
首先Qt本身就有一個(gè)系統(tǒng)托盤的類,?QSystemTrayIcon類。
所以第一步:創(chuàng)建該類的對(duì)象,為該對(duì)象設(shè)置圖標(biāo),然后show出來,托盤圖標(biāo)就能顯示了。
第二步:要想右擊的時(shí)候糖醋一個(gè)菜單欄,需要調(diào)用QSystemTrayIcon類的setContextMenu()函數(shù),此時(shí)需要添加一個(gè)菜單欄就行了。
所以接下來看具體代碼。
3.具體代碼以及解釋
需要加頭文件
#include "qsystemtrayicon.h"
#include<qmenu.h>
.h文件中創(chuàng)建相應(yīng)的對(duì)象:
QMenu* m_pTrayMennu; //系統(tǒng)托盤右鍵菜單項(xiàng)
QSystemTrayIcon* m_pSystemTray; //系統(tǒng)托盤圖標(biāo)
//右鍵菜單欄選項(xiàng)
QAction* m_pActionShow;
QAction* m_pActionHide;
QAction* m_pActionModel;
QAction* m_pActionSetting;
QAction* m_pActionQuit;
.cpp文件:
void CDesktopPet::CreatSystemTray()
{
//創(chuàng)建菜單對(duì)象和托盤圖標(biāo)對(duì)象
m_pTrayMennu = new CTrayMenu(this);
m_pSystemTray = new QSystemTrayIcon(this);
//創(chuàng)建菜單項(xiàng)
m_pActionShow = new QAction(tr("Show pet"), this);
m_pActionHide = new QAction(tr("Hide pet"), this);
m_pActionModel = new QAction(tr("Model selecte"), this);
m_pActionSetting = new QAction(tr("Setting"), this);
m_pActionQuit = new QAction(tr("Exit"), this);
//添加菜單項(xiàng)
m_pTrayMennu->addAction(m_pActionShow);
m_pTrayMennu->addAction(m_pActionHide);
m_pTrayMennu->addAction(m_pActionModel);
m_pTrayMennu->addAction(m_pActionSetting);
m_pTrayMennu->addSeparator();
m_pTrayMennu->addAction(m_pActionQuit);
//為系統(tǒng)托盤設(shè)置菜單為m_pTrayMennu
m_pSystemTray->setContextMenu(m_pTrayMennu);
m_pSystemTray->setIcon(QIcon(":/CDesktopPet/Resource/image/trayIcon.png"));
m_pSystemTray->show();
}
這是全部代碼,需要注意的是最后三句代碼:
1.?m_pSystemTray->setContextMenu(m_pTrayMennu);系統(tǒng)托盤類對(duì)象設(shè)置上下文菜單為(m_pTrayMennu);
2.?m_pSystemTray->setIcon(QIcon(":/CDesktopPet/Resource/image/trayIcon.png"));系統(tǒng)托盤類對(duì)象對(duì)象設(shè)置圖標(biāo),這個(gè)必須有,不設(shè)置圖標(biāo)是顯示不出來的。
3.?m_pSystemTray->show();顯示系統(tǒng)托盤類對(duì)象。
在新建項(xiàng)目的界面類的構(gòu)造函數(shù)里調(diào)用CreatSystemTray()函數(shù),就可以了!
如果還想把任務(wù)欄的系統(tǒng)圖標(biāo)給隱藏掉,可以加上這句:文章來源:http://www.zghlxwxcb.cn/news/detail-402725.html
setWindowFlags(Qt::Tool);
4.總結(jié)
該功能實(shí)現(xiàn)起來還是比較簡(jiǎn)單,其實(shí)還有很多后續(xù)工作需要繼續(xù)完善,比如點(diǎn)擊了退出菜單項(xiàng),將程序退出;這個(gè)實(shí)現(xiàn)需要添加槽函數(shù),來接受右鍵菜單項(xiàng)的信號(hào),在相應(yīng)的槽函數(shù)中直接調(diào)用退出函數(shù)QApplication::exit(0);即可,在此小小記錄一下。文章來源地址http://www.zghlxwxcb.cn/news/detail-402725.html
到了這里,關(guān)于Qt實(shí)現(xiàn)最小化窗口到托盤圖標(biāo)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!