来看一个小例子
// 重写鼠标右键事件
void QtGuiApplication2::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::RightButton)
{
m_pMenuRD->exec(QCursor::pos());
}
}
鼠标右键启动菜单,菜单里面有啥呢?
// 先来声明一下
// 右键菜单
QMenu* m_pMenuRD;
QAction* m_pActionAdd;
QAction* m_pActionDelete;
QAction* m_pActionEdit;
//初始化一下
// 测试菜单
QMenu* m_pMenuTest;
QAction* m_pActionTest1;
QAction* m_pActionTest2;
// 右键菜单
m_pMenuRD = new QMenu(this);
m_pActionAdd = m_pMenuRD->addAction(tr("Add"));
m_pActionDelete = m_pMenuRD->addAction(tr("Delete"));
m_pActionEdit = m_pMenuRD->addAction(tr("Edit"));
m_pMenuRD->addSeparator();
// 测试菜单
m_pMenuTest = new QMenu(this);
m_pMenuTest->setTitle(tr("Test"));
m_pActionTest1 = m_pMenuTest->addAction(tr("Test1"));
m_pActionTest2 = m_pMenuTest->addAction(tr("Test2"));
m_pMenuRD->addMenu(m_pMenuTest);
connect(m_pMenuRD, &QMenu::triggered, this, &QtGuiApplication2::SlotMenuClicked);
// 这是你要做的事
void QtGuiApplication2::SlotMenuClicked(QAction* action)
{
if (action == m_pActionAdd)
{
ui.m_pLabel->setText(tr("Add"));
}
else if (action == m_pActionDelete)
{
ui.m_pLabel->setText(tr("Delete"));
}
else if (action == m_pActionTest1)
{
ui.m_pLabel->setText(tr("Test1"));
}
}
嗯,挺简单的,但是不熟的人可能觉得挺难的。因为我相信一个道理,世界上的困难事的一半的难度来源于不熟悉。