最近在開發(fā)項(xiàng)目時(shí)用到鼠標(biāo)右鍵創(chuàng)建菜單的功能,在此做一些記錄。
功能描述:QT實(shí)現(xiàn)點(diǎn)擊鼠標(biāo)右鍵創(chuàng)建菜單,菜單帶圖標(biāo),并且可以點(diǎn)擊菜單欄選項(xiàng),出現(xiàn)相應(yīng)的界面。效果如下圖所示:

實(shí)現(xiàn)原理:要實(shí)現(xiàn)上圖效果,我用到QMenu,創(chuàng)建菜單項(xiàng),將菜單項(xiàng)加入菜單,然后關(guān)聯(lián)菜單項(xiàng)按鈕和相應(yīng)的槽函數(shù)。
代碼:
1.實(shí)現(xiàn)菜單
? ? QMenu *pMenu = new QMenu(this);? ? //菜單初始化
pMenu->setStyleSheet("background-color:#1a1a1a;color:#fff;");? ? //設(shè)置菜單樣式背景顏色
? ? //設(shè)置菜單項(xiàng)
QAction *pSettask = new QAction(tr("任務(wù)設(shè)置"),this);
QAction *pEquipdebug = new QAction(tr("設(shè)備調(diào)試"),this);
QAction *pCommucontrol = new QAction(tr("通信控制"),this);
QAction *pClustercontrol = new QAction(tr("集群控制"),this);
? ? //將菜單項(xiàng)加入菜單
? ? pMenu->addAction(pSettask);
pSettask->setIcon(QIcon(":/new/prefix1/icon/205設(shè)置.png"));? ? //設(shè)置菜單圖標(biāo)
pSettask->setIconVisibleInMenu(true);? ? ?? //圖標(biāo)設(shè)置為可見
pMenu->addSeparator();? //設(shè)置菜單項(xiàng)之間的分隔線
? ? //其余項(xiàng)設(shè)置方法相同
pMenu->addAction(pEquipdebug);
pEquipdebug->setIcon(QIcon(":/new/prefix1/icon/調(diào)試.png"));
pEquipdebug->setIconVisibleInMenu(true);
pMenu->addSeparator();
pMenu->addAction(pCommucontrol);
pCommucontrol->setIcon(QIcon(":/new/prefix1/icon/通訊錄.png"));
pCommucontrol->setIconVisibleInMenu(true);
pMenu->addSeparator();
pMenu->addAction(pClustercontrol);
pClustercontrol->setIcon(QIcon(":/new/prefix1/icon/集群.png"));
pClustercontrol->setIconVisibleInMenu(true);
? ? //菜單項(xiàng)按鈕關(guān)聯(lián)槽函數(shù)
? ? console *con = new console;? ? //初始化要連接到的模塊
connect(pSettask,&QAction::triggered,con,&console::on_stackedWidget_3_currentChanged);
connect(pEquipdebug,&QAction::triggered,con,&console::on_stackedWidget_3_currentChanged);
connect(pCommucontrol,&QAction::triggered,con,&console::on_stackedWidget_3_currentChanged);
connect(pClustercontrol,&QAction::triggered,con,&console::on_stackedWidget_3_currentChanged);
//在鼠標(biāo)右鍵點(diǎn)擊的地方顯示菜單
pMenu->exec(cursor().pos());
2.菜單關(guān)聯(lián)的槽函數(shù)
void console::on_stackedWidget_3_currentChanged(int arg1)
{
QAction *pEven = qobject_cast<QAction*>(this->sender());? ? //獲取是由哪個菜單項(xiàng)按鈕發(fā)出的信號
if(pEven->text().contains("任務(wù)設(shè)置"))
{
ui->stackedWidget_3->setCurrentWidget(ui->page_5);
}
if(pEven->text().contains("設(shè)備調(diào)試"))
{
ui->stackedWidget_3->setCurrentWidget(ui->page_7);
}
if(pEven->text().contains("通信控制"))
{
ui->stackedWidget_3->setCurrentWidget(ui->page_9);
}
else if(pEven->text().contains("集群控制"))
{
ui->stackedWidget_3->setCurrentWidget(ui->page_10);
}
show();
}
總結(jié):
菜單的創(chuàng)建函數(shù)從Ui文件中的widget控件中,右鍵轉(zhuǎn)到槽函數(shù)得來。
項(xiàng)目中的右鍵菜單效果我用的照片,所以分隔線的效果不是特別明顯,四個菜單項(xiàng)需要三條分隔線。文章來源:http://www.zghlxwxcb.cn/news/detail-557064.html
圖標(biāo)素材需要添加到資源庫。文章來源地址http://www.zghlxwxcb.cn/news/detail-557064.html
到了這里,關(guān)于QT實(shí)現(xiàn)鼠標(biāo)點(diǎn)擊鼠標(biāo)右鍵創(chuàng)建菜單(帶圖標(biāo))的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!