有时我们希望在窗口中右键弹出菜单,这里来介绍一下QT中怎么实现.
.h 中添加事件相应函数声明和变量定义:
private:
// 菜单事件
void contextMenuEvent(QContextMenuEvent* event) override;
void initMenu();
private:
QMenu* m_pMenu = nullptr;
在构造函数中设置菜单选项
// 设置菜单策略
this->setContextMenuPolicy(Qt::DefaultContextMenu);
this可以改为其它组件指针,这样就可以在指定组件内右键才弹出菜单。这里指在整个窗口右键都会弹出菜单。
菜单内容的初始化实现:
void Widget::initMenu()
{
m_pMenu = new QMenu(this);
QAction *pAc1 = new QAction("ac1");
QAction *pAc2 = new QAction("ac2");
QAction *pAc3 = new QAction("ac3");
QAction *pAc4 = new QAction("ac4");
QAction *pAc5 = new QAction("ac5");
m_pMenu->addAction(pAc1);
m_pMenu->addAction(pAc2);
m_pMenu->addAction(pAc3);
m_pMenu->addAction(pAc4);
m_pMenu->addAction(pAc5);
connect(pAc1, &QAction::triggered, [=]{
QMessageBox::information(this, "title", "ac1");
});
connect(pAc2, &QAction::triggered, [=]{
QMessageBox::information(this, "title", "ac2");
});
connect(pAc3, &QAction::triggered, [=]{
QMessageBox::information(this, "title", "ac3");
});
connect(pAc4, &QAction::triggered, [=]{
QMessageBox::information(this, "title", "ac4");
});
connect(pAc5, &QAction::triggered, [=]{
QMessageBox::information(this, "title", "ac5");
});
}
菜单的响应函数:
void Widget::contextMenuEvent(QContextMenuEvent* event)
{
m_pMenu->exec(QCursor::pos());
}
实现如下图:
源代码实现: