QT中右键菜单

实现方法有四种种:

第一种方法:使用Qt::DefaultContextMenu 通过重写 contextMenuEvent来实现

使用QMenu、QAction 通过重写contextMenuEvent 来实现。
链接中还有其他的方式实现

protected:

    QAction *m_pAddNew;
    QAction *m_pDelete;
    QMenu *m_pMenu;
    void contextMenuEvent(QContextMenuEvent *event);
NewTestForm::NewTestForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NewTestForm)
{
    ui->setupUi(this);
    //添加右键 快捷菜单


    m_pMenu = new QMenu(this);


    m_pAddNew = new QAction("add new", this);
    m_pDelete = new QAction("delete", this);




    m_pMenu->addAction(m_pAddNew);
    m_pMenu->addAction(m_pDelete);
    //setContextMenuPolicy(Qt::ActionsContextMenu);


    //消息响应
    connect(m_pAddNew, &QAction::triggered,this,[=](){
        qDebug()<<"show this position--add";
    });


    connect(m_pDelete, &QAction::triggered,this,[=](){
        qDebug()<<"show this position--delete";
    });
}
void NewTestForm::contextMenuEvent(QContextMenuEvent *event)
{
    m_pMenu->exec(QCursor::pos());
    event->accept();
}

第二种:使用鼠标事件进行

void NewTestForm::mousePressEvent(QMouseEvent *event)
{


    if(event->button() == Qt::RightButton)
    {
        //m_pMenu->exec(event->pos());//fail
        //m_pMenu->exec(event->globalPos());//ok
        m_pMenu->exec(QCursor::pos());//ok//相对于屏幕的坐标
    }
    }

注意:QAction *QMenu::exec()

中必须使用全局坐标,详情请看QT的帮助

其中,使用event->pos()时,鼠标点击时的坐标,与界面显示坐标不一致。当使用globalPos() 和 QCursor::pos() 时 弹出的菜单栏与原来一致。

参考资料
C++培训之Qt右键菜单的添加
http://www.itcast.cn/news/20151228/16362379744.shtml

Qt之自定义菜单(右键菜单)
http://blog.sina.com.cn/s/blog_a6fb6cc90101f0xn.html

Qt右键创建菜单(包含二级菜单)
https://blog.youkuaiyun.com/u011624093/article/details/81157279?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

qt 右键菜单
https://blog.youkuaiyun.com/abigale_zhw/article/details/8235560

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值