QMenu

最后更新于:2022-04-02 02:10:31

[TOC] ## 概述 实例 ``` //创建右键菜单对象 m_menuContext = new QMenu(tr("ContextMenu")); //右键菜单其实不显示ContextMenu文本 //创建“添加条目”菜单项并添加到菜单 QAction *actAdd = new QAction(tr("添加条目"), this); m_menuContext->addAction( actAdd ); //创建“编辑条目”菜单项并添加到菜单 QAction *actEdit = new QAction(tr("编辑条目"), this); m_menuContext->addAction( actEdit ); //创建“删除条目”菜单项并添加到菜单 QAction *actDel = new QAction(tr("删除条目"), this); m_menuContext->addAction( actDel ); //创建“清空所有”菜单项并添加到菜单 QAction *actClearAll = new QAction(tr("清空所有"), this); m_menuContext->addAction( actClearAll ); connect(ui->listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomContextMenuRequested(QPoint)) ); //为四个菜单项关联点击信号到槽函数 connect(actAdd, SIGNAL(triggered()), this, SLOT(onAddItemTriggered())); connect(actEdit, SIGNAL(triggered()), this, SLOT(onEditItemTriggered())); connect(actDel, SIGNAL(triggered()), this, SLOT(onDelItemTriggered())); connect(actClearAll, SIGNAL(triggered()), this, SLOT(onClearAllTriggered())); ``` 设置右键弹出菜单 ``` void Widget::onCustomContextMenuRequested(const QPoint & pos) { //控件内的相对坐标转为屏幕坐标 //是列表控件发出的信号,就用列表控件的转换函数 QPoint screenPos = ui->listWidget->mapToGlobal( pos ); //弹出菜单 QAction *actRet = m_menuContext->exec( screenPos ); if(NULL != actRet)//检查非空才能使用该指针 { qDebug()<text(); } } ``` 弹出右键菜单的槽函数 ``` void Widget::onCustomContextMenuRequested(const QPoint & pos) { //控件内的相对坐标转为屏幕坐标 //是列表控件发出的信号,就用列表控件的转换函数 QPoint screenPos = ui->listWidget->mapToGlobal( pos ); //弹出菜单 QAction *actRet = m_menuContext->exec( screenPos ); if(NULL != actRet)//检查非空才能使用该指针 { qDebug()<text(); } } ```
';