Qt 實現多級選單
阿新 • • 發佈:2019-01-31
前言
在眾多知名的軟體UI中下拉選單、按鈕選單、右鍵選單、托盤選單、多級選單等等是很常見的,就連Windows和linux等系統級的軟體也用到這些UI元素。下圖就是我們最常見的Windows系統多級選單:Qt實現(多級)選單
在Qt中通過QMenu和QAction就可以實現這些選單,QMenu就是上圖中我們看到的三個級聯選單,每個QMenu裡面的小專案就是一個QAction,一個QAction由一個圖示和一段文字描述組成。要先右鍵彈出選單我們需要重寫contextMenuEvent(QContextMenuEvent *event)事件,如果是按鈕選單等關聯訊號槽,在槽函式彈出選單即可。原始碼分析
- void Widget::createMenu()
- {
- m_menu1 = new QMenu();
- m_menu1->addAction("1_1",this,SLOT(actionsSlot()));
- m_menu1->addAction("1_2",this,SLOT(actionsSlot()));
- m_menu1->addAction("1_3",this,SLOT(actionsSlot()));
- QMenu* menu2 = m_menu1->addMenu("2_0");
- menu2->addAction("2_1"
- QMenu* menu3 = menu2->addMenu("3_0");
- menu2->addSeparator();
- menu3->addAction("3_1",this,SLOT(actionsSlot()));
- menu3->addAction("3_2",this,SLOT(actionsSlot()));
- menu3->addAction("3_3",this,SLOT(actionsSlot()));
- menu2->addAction("2_2"
- menu2->addAction("2_3",this,SLOT(actionsSlot()));
- m_menu1->addSeparator();
- m_menu1->addAction("1_4",this,SLOT(actionsSlot()));
- }
- void Widget::actionsSlot()
- {
- QAction *action = (QAction*)sender();
- QString actionText = action->text();
- qDebug()<<actionText<<"triggerred!"<<endl;
- if("1_1" == actionText) {
- //...
- } elseif("1_2" == actionText) {
- //...
- }
- //...
- }
- void Widget::contextMenuEvent(QContextMenuEvent *event)
- {
- m_menu1->exec(QCursor::pos());
- event->accept();
- }