Use of context menus (beginner)
The context menu is popup by right-clicking the mouse button. The main description under the basic context menu is how the framework should be written.
As long as the menu-related operations generally use qmenu and qaction can be resolved.
Method 1 is implemented by overriding Contextmenuevent (Qcontextmenuevent *e)
void MainWindow::contextMenuEvent*e){ popmenu->addAction(copyAction); popmenu->addAction(pasteAction); popmenu->addAction(deletAction); popmenu->exec(QCursor::pos()); e->accept();}
The complete code is as follows
. h
#ifndef Mainwindow_h#define mainwindow_h#include <QMainWindow>#include <QContextMenuEvent>Namespace Ui {class MainWindow;} Class MainWindow: Publicqmainwindow{Q_object Public:Explicit MainWindow(Qwidget *parent =0); ~mainwindow ();protected:Private: Ui::mainwindow *ui; Qmenu *popmenu; Qaction *copyaction; Qaction *pasteaction; Qaction *deletaction;voidContextmenuevent (Qcontextmenuevent *);};#endif //Mainwindow_h
. cpp
#include "mainwindow.h"#include "ui_mainwindow.h"Mainwindow::mainwindow (Qwidget *parent): Qmainwindow (parent), UI (NewUi::mainwindow) {Ui->setupui ( This); Popmenu =NewQmenu ( This); Copyaction =NewQaction ("Copy", This); Pasteaction =NewQaction ("Paste", This); Deletaction =NewQaction ("Delete", This); Copyaction->seticon (Qicon (":/icon/copy.png")); Pasteaction->seticon (Qicon (":/icon/parst.png")); Deletaction->seticon (Qicon (":/icon/delet.png"));} Mainwindow::~mainwindow () {Delete UI;}voidMainwindow::contextmenuevent (qcontextmenuevent *e) {popmenu->addaction (copyaction); Popmenu->addaction (pasteaction); Popmenu->addaction (deletaction);//The position of the popup is the position of the current cursorPopmenu->exec (qcursor::p OS ()); E->accept ();}
Method 2
By adding the action directly in the constructor
Then use Setcontextmenupolicy to set to Actionscontextmenu
copyaction = new Qaction ( "copy" , this); Pasteaction = new qaction ( "paste" , this); Deletaction = new qaction ( "delete" , this); Copyaction-> SetIcon (Qicon ()); Pasteaction-> SetIcon (Qicon ()); Deletaction-> SetIcon (Qicon ()); Addaction (copyaction); Addaction (pasteaction); Addaction (deletaction); Setcontextmenupolicy (Qt::actionscontextmenu );
The effect is as follows:
Qt context Menu