1. 修改右键菜单策略
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
addAction(new QAction("新增",this));
addAction(new QAction("删除",this));
setContextMenuPolicy(Qt::ActionsContextMenu);
}
构造函数中直接用addAction添加了两个菜单项,setContextMenuPolicy(Qt::ActionsContextMenu)这一句是启动右键菜单策略,然后运行右击就会有菜单弹出。运行如下。
2. 重写mousePressEvent()方法。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_contextMenu = new QMenu; //这是右击弹出的菜单
m_addAction = new QAction("新增",this);
m_delAction = new QAction("删除",this);
//给菜单添加菜单项
m_contextMenu->addAction(m_addAction);
m_contextMenu->addAction(m_delAction);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
//确保右键点击,然后跳出菜单.
if (event->button() == Qt::RightButton)
{
//在鼠标右击的地方弹出菜单
m_contextMenu->exec(event->globalPos());
}
event->accept();
}
3. 重写contextMenuEvent()
同2,只需要把mousePressEvent()换成contextMenuEvent();具体代码如下。
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
//让菜单移动到鼠标位置并显示.
m_contextMenu->exec(event->globalPos());
}