【QT开发笔记-基础篇】| 第四章 事件QEvent | 4.9 右键菜单事件

本节对应的视频讲解:B_站_链_接

【QT开发笔记-基础篇】 第4章 事件 4.9 右键菜单事件


本章要实现的整体效果如下:

整体效果

QEvent::ContextMenu

​ 在窗口/控件上点击鼠标右键时,触发该事件,它对应的子类是 QContextMenuEvent


首先,在 context_widget.h 中声明几个 QAction、槽函数以及 contextMenuEvent() 函数:

#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, SIGNAL(triggered()), this, SLOT(slotAction()));
    connect(copy, SIGNAL(triggered()), this, SLOT(slotAction()));
    connect(paste, SIGNAL(triggered()), this, SLOT(slotAction()));
    connect(toUpper, SIGNAL(triggered()), this, SLOT(slotAction()));
    connect(toLower, SIGNAL(triggered()), this, SLOT(slotAction()));
    connect(hide, SIGNAL(triggered()), this, SLOT(slotAction()));
}

然后,实现槽函数:

void ContextWidget::slotAction()
{
    QAction* act = (QAction*)(sender());
#if 0
    if ( act == cut ) {
        qDebug() << "slot_cut";
    }
#endif
    qDebug() << act->text();
}


这里使用 QObject 类的 sender() 函数,返回发送该信号的对象


最后,实现 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;
}

此时运行结果,就可以弹出菜单,并执行相对于菜单的功能(这里仅仅是打印菜单的文本):

运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大轮明王讲QT

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值