Qt想要实现右键菜单,只需要重写如下函数即可:

void contextMenuEvent(QContextMenuEvent *event);

运行效果:

Qt--右键菜单_#include

示例如下:

==mainwindow.h ==

#ifndef
#define

#include <QMainWindow>
#include <QContextMenuEvent>
#include <QMenu>
#include <QAction>
#include <QDebug>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void contextMenuEvent(QContextMenuEvent *event);

public slots:
void slot_action1();
void slot_action2();
void slot_action3();
void slot_action4();
void slot_action5();

private:
Ui::MainWindow *ui;
QAction *action1;
QAction *action2;
QAction *action3;
QAction *action4;
QAction *action5;
};
#endif// MAINWINDOW_H

==mainwindow.cpp ==

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
action1 = new QAction(tr("打开文件"),this);
action2 = new QAction(tr("打开文件夹"),this);
action3 = new QAction(tr("关闭文件"),this);
action4 = new QAction(tr("关闭文件夹"),this);
action5 = new QAction(tr("保存文件"),this);

connect(action1,SIGNAL(triggered()),this,SLOT(slot_action1()));
connect(action2,SIGNAL(triggered()),this,SLOT(slot_action2()));
connect(action3,SIGNAL(triggered()),this,SLOT(slot_action3()));
connect(action4,SIGNAL(triggered()),this,SLOT(slot_action4()));
connect(action5,SIGNAL(triggered()),this,SLOT(slot_action5()));
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
Q_UNUSED(event)
QMenu *menu = new QMenu(this);
menu->addAction(action1);
menu->addAction(action2);
menu->addAction(action3);
menu->addAction(action4);
menu->addAction(action5);
menu->exec(QCursor::pos());
}

void MainWindow::slot_action1()
{
qDebug()<<"打开文件";
}
void MainWindow::slot_action2()
{
qDebug()<<"打开文件夹";
}
void MainWindow::slot_action3()
{
qDebug()<<"关闭文件";
}
void MainWindow::slot_action4()
{
qDebug()<<"关闭文件夹";
}
void MainWindow::slot_action5()
{
qDebug()<<"保存文件";
}