有时我们希望在窗口中右键弹出菜单,这里来介绍一下QT中怎么实现,首先创建一个MainWindow项目。
1、在mainwindow.h
文件中添加槽声明
private slots:
void on_MainWindow_customContextMenuRequested(const QPoint &pos);
- 槽函数的名字固定,QT内部已经设置好了其对应的触发信号,不同的窗口类名将函数名中的
Mainwindow
替换一下即可
2、在构造函数中设置上下文菜单选项
this->setContextMenuPolicy(Qt::CustomContextMenu);
this
可以改为其它组件指针,这样就可以在指定组件内右键才弹出菜单。这里指在整个窗口右键都会弹出菜单。
3、在mainwindow.cpp
文件中编写槽函数
void MainWindow::on_MainWindow_customContextMenuRequested(const QPoint &pos)
{
QString tmp;
QMenu *pMenu = new QMenu(this);
QAction *mes = new QAction(tr("信息"), this);
QAction *quit = new QAction(tr("退出"), this);
/* 添加菜单项 */
pMenu->addAction(mes);
pMenu->addAction(quit);
/* 连接槽函数 */
connect(mes, SIGNAL(triggered()), this, SLOT(message()));
connect(quit, SIGNAL(triggered()), this, SLOT(close())); //直接触发窗口的close函数
/* 在鼠标右键处显示菜单 */
pMenu->exec(cursor().pos());
/* 释放内存 */
QList<QAction*> list = pMenu->actions();
foreach (QAction* pAction, list) delete pAction;
delete pMenu;
}
4、在mainwindow.h
文件中添加触发槽函数
private slots:
void message();
5、在mainwindow.cpp
文件中编写message
函数
#include <QMessageBox>
void MainWindow::message()
{
QMessageBox::information(this,"info", "信息");
}
效果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)