在qt中,关于右键弹出菜单,有几种实现方法:
1-在窗口初始化时,修改指定控件的右键菜单策略,然后把右键点击信号和某个槽函数连接。
//设置btnNew按钮的右键菜单策略
ui->btnNew->setContextMenuPolicy(Qt::CustomContextMenu);
//把btnNew按钮的右键点击信号和槽函数连接
connect(ui->btnNew,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(on_btnNew_clicked()));
2-在窗口初始化时,给指定控件安装事件过滤器,然后重写窗口的eventFilter接口函数。
//设置btnSave按钮的事件过滤器
ui->btnSave->installEventFilter(this);
窗口头文件加入eventFilter接口函数的声明: protected:
bool eventFilter(QObject *watched, QEvent *event);
窗口实现文件eventFilter接口函数:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
//检测btnSave按钮的右键菜单事件
if (watched == ui->btnSave && event->type() == QEvent::ContextMenu)
{
QMenu * menu=new QMenu;
QAction * saveaction=new QAction;
saveaction->setText("保存按钮右键");
menu->addAction(saveaction);
menu->exec(QCursor::pos());
return true;
}
//注意,最后要调用基类QObject的eventFilter接口,否则窗口无法响应
return QObject::eventFilter(watched,event);
}
3-后面两种,跟上边一样,也是在窗口中重写派生保护函数contextMenuEvent和mousePressEvent。
窗口头文件加入这两个函数的声明:
protected:
void contextMenuEvent(QContextMenuEvent *event);
void mousePressEvent(QMouseEvent *event);
窗口实现文件:
//重写窗口contextMenuEvent函数实现label右键菜单
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
//把鼠标位置转化成相对于label的位置
QPoint i = ui->labelSnapshot->mapFromGlobal(event->globalPos());
//获取label的尺寸
QRect rect(QPoint(0,0),ui->labelSnapshot->size());
//然后判断鼠标位置是否在label内.
if (rect.contains(i))
{
QMenu * menu=new QMenu;
QAction * saveaction=new QAction;
saveaction->setText("label另存");
connect(saveaction,SIGNAL(triggered(bool)),this,SLOT(on_btnSave_clicked()));
menu->addAction(saveaction);
menu->exec(event->globalPos());
}
}
//重写窗口mousePressEvent函数实现text右键菜单
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->buttons()==Qt::RightButton)
{
//把鼠标位置转化成相对于text的位置
QPoint i = ui->textEdit->mapFromGlobal(event->globalPos());
//获取text的尺寸
QRect rect(QPoint(0,0),ui->textEdit->size());
//然后判断鼠标位置是否在text内.
if (rect.contains(i))
{
QMenu * menu=new QMenu;
QAction * saveaction=new QAction;
saveaction->setText("text另存");
connect(saveaction,SIGNAL(triggered(bool)),this,SLOT(on_btnSave_clicked()));
menu->addAction(saveaction);
menu->exec(event->globalPos());
}
}
}