QT中實現上下文菜單

在許多的應用程序中,當我們右擊時會彈出一個菜單,這個菜單就叫做“上下文菜單”,英文名稱爲“Context Menu”.在QT中有兩種方式可以實現這種上下文菜單,一一列舉如下:

   一.重載contextMenuEvent()函數,一個簡單的示例如下:

 

void MainWindow::contextMenuEvent(QContextMenuEvent *event)

{

  filemenu->addAction(newAction);

  filemenu->addAction(editAction);

  filemenu->addAction(delAction);

  filemenu->exec(QCursor::pos());         //位於鼠標點擊處

  //filemenu->exec(this->mapToGlobal(QPoint(0,0)));

//位於父組件的(0,0)座標處

  //event->accept();//有時候需要加上這句,因爲許多情況下默認爲ignore事件

}

 

  二.在類的構造函數中進行相關設置,如我們可以定義如下函數,再在構造函數中調用它

 

void MainWindow::createContextMenu()

{

  addAction(newAction);

  addAction(editAction);

  addAction(delAction);

  setContextMenuPolicy(Qt::ActionsContextMenu);

}

 

 

   其中

Qt::ActionsContextMenu是位於Qt命名空間的一個枚舉類型,它的定義爲:

  enum Qt::ContextMenuPolicy

  This enum type defines the various policies a widget can have with respect to showing a context menu.

Qt::NoContextMenu        0     the widget does not feature a context menu, context menu handling is deferred to the widget's parent.

Qt::DefaultContextMenu   1     the widget's QWidget::contextMenuEvent() handler is  called.

Qt::ActionsContextMenu   2     the widget displays its QWidget::actions() as context menu.

Qt::CustomContextMenu    3     the widget emits the QWidget::customContextMenuRequested() signal.

Qt::PreventContextMenu   4     the widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget's parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through mousePressEvent(), and mouseReleaseEvent().

   今天又在書上看到這麼一段話,剛好可以用在這裏,首先來看一下這段話:

 

   Creating modal dialogs and context menus in QWidget::contextMenuEvent() reimplementations on the stack is a common programming pattern since we usually don't need the dialog or menu after we have used it,and it will automatically be destroyed at the end of the enclosing scope.

 

  根據這段話所說,我們要對程序進行修改的話,只需要把QMenu與QAction的實例化放在相應的函數裏面,可以直接用一個變量,也可以用new,不過用new的時候要記得在函數結尾處要調用delete。這個比較簡單,就不在這裏列出相應的代碼了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章