右键菜单事件(QEvent::ContextMenu)在窗口/控件上点击鼠标右键时,触发该事件,它对应的子类是QContextMenuEvent
本节实现一个右键菜单功能,效果如下:
image-20260820122243893

1. 创建右键菜单

首先,在context_widget.h 中声明相关成员变量和函数,如下:

#include <QContextMenuEvent>

#include <QMenu>
#include <QAction>
#include <QCursor>

class ContextWidget : public QWidget
{
private slots:
    void slotAction();

protected:
    void contextMenuEvent(QContextMenuEvent* event);

private:
    QAction* cut;
    QAction* copy;
    QAction* paste;
    QAction* toUpper;
    QAction* toLower;
    QAction* hide;
};

然后,在context_widget.cpp 的构造中,创建QAction 并关联槽函数:

ContextWidget::ContextWidget(QWidget* parent) : QWidget{parent}
{
    cut = new QAction("剪切(T)", this);
    copy = new QAction("复制(C)", this);
    paste = new QAction("粘贴(P)", this);
    toUpper = new QAction("转成大写(U)", this);
    toLower = new QAction("转成小写(L)", this);
    hide = new QAction("隐藏行", this);

    connect(cut, &QAction::triggered, this, &ContextWidget::slotAction);
    connect(copy, &QAction::triggered, this, &ContextWidget::slotAction);
    connect(paste, &QAction::triggered, this, &ContextWidget::slotAction);
    connect(toUpper, &QAction::triggered, this, &ContextWidget::slotAction);
    connect(toLower, &QAction::triggered, this, &ContextWidget::slotAction);
    connect(hide, &QAction::triggered, this, &ContextWidget::slotAction);
}

最后,实现slotAction()槽函数,如下:

void ContextWidget::slotAction()
{
    // QObject 类的 sender() 函数,返回发送该信号的对象
    QAction* act = (QAction*)(sender());
#if 0
    if ( act == cut ) {
        qDebug() << "slot_cut";
    }
#endif
    qDebug() << act->text();
}

2. 弹出右键菜单

实现contextMenuEvent()函数

void ContextWidget::contextMenuEvent(QContextMenuEvent* event)
{
    QMenu* menu = new QMenu();

    menu->setFixedWidth(160);  //菜单栏显示宽度
    menu->addAction(cut);
    menu->addAction(copy);
    menu->addAction(paste);
    menu->addSeparator();
    menu->addAction(toUpper);
    menu->addAction(toLower);
    menu->addSeparator();
    menu->addAction(hide);

    menu->exec(event->globalPos());

    delete menu;
}

此时,运行结果:
image-20260820122401813