Qt 上下文菜单

上下文菜单的使用(初级)

上下文菜单可通过鼠标右键点击弹出。主要描述下基本的上下文菜单的框架应该怎么写。
只要涉及菜单的操作一般使用 QMenu 和QAction 都能够解决。

方法1

通过重写contextMenuEvent(QContextMenuEvent *e)实现
void MainWindow::contextMenuEvent(QContextMenuEvent *e)
{
    popmenu->addAction(copyAction);
    popmenu->addAction(pasteAction);
    popmenu->addAction(deletAction);
    popmenu->exec(QCursor::pos());
    e->accept();
}

完整代码如下

.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:

private:
    Ui::MainWindow *ui;
    QMenu *popmenu;
    QAction *copyAction;
    QAction *pasteAction;
    QAction *deletAction;
    void contextMenuEvent(QContextMenuEvent *);

};

#endif // MAINWINDOW_H
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    popmenu = new QMenu(this);
    copyAction = new QAction("copy",this);
    pasteAction = new QAction("paste",this);
    deletAction = new QAction("delete",this);
    copyAction->setIcon(QIcon(":/Icon/copy.png"));
    pasteAction->setIcon(QIcon(":/Icon/parst.png"));
    deletAction->setIcon(QIcon(":/Icon/delet.png"));
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::contextMenuEvent(QContextMenuEvent *e)
{
    popmenu->addAction(copyAction);
    popmenu->addAction(pasteAction);
    popmenu->addAction(deletAction);
    //弹出的位置为当前光标的位置
    popmenu->exec(QCursor::pos());
    e->accept();
}

方法2

通过在构造函数中直接加入action
然后使用setContextMenuPolicy设置为ActionsContextMenu

    copyAction = new QAction("copy",this);
    pasteAction = new QAction("paste",this);
    deletAction = new QAction("delete",this);
    copyAction->setIcon(QIcon(":/Icon/copy.png"));
    pasteAction->setIcon(QIcon(":/Icon/parst.png"));
    deletAction->setIcon(QIcon(":/Icon/delet.png"));
    addAction(copyAction);
    addAction(pasteAction);
    addAction(deletAction);
    setContextMenuPolicy(Qt::ActionsContextMenu);

效果如下:
Qt 上下文菜单_第1张图片

你可能感兴趣的:(qt,菜单,qt上下文菜单,menu,Qmenu,上下文菜单)