// myWidget is any QWidget-derived class
myWidget->setContextMenuPolicy(Qt::CustomContextMenu)
connect(myWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&)))
void MyClass::ShowContextMenu(const QPoint& pos) // this is a slot
{
// for most widgets
QPoint globalPos = myWidget->mapToGlobal(pos)
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos)
QMenu myMenu
myMenu.addAction("Menu Item 1")
// ...
QAction* selectedItem = myMenu.exec(globalPos)
if (selectedItem)
{
// something was chosen, do stuff
}
else
{
// nothing was chosen
}
}
Solution 1 :给一个 QWidget 添加 QActions,设置QWidget 的 contextMenuPolicy 属性为 Qt::ActionsContextMenu 值,使得窗口菜单以这些添加的 QActions 为菜单项组成一个右键菜单。1:MyWidget::MyWidget(QWidget *parent)2:: QWidget(parent)3:{4:setWindowTitle(tr(Context Menu Show 1))5://为窗口添加QActions6:addAction(newQAction(tr(&Open),this))7:addAction(newQAction(QIcon(:/images/mark.png), tr(&Mark),this))8:addAction(newQAction(tr(&Quit),this))9://设置contextMenuPolicy属性值为 '以Actions为d出菜单的菜单项组成菜单'10:setContextMenuPolicy(Qt::ActionsContextMenu)11:}效果:Solution 2 :重写 QWidget 的被保护的虚函数void QWidget::contextMenuEvent (QContextMenuEvent*event)[virtual protected],设置QWidget 的 contextMenuPolicy 属性为 Qt::DefaultContextMenu 值,其实默认就是这个值,不用显示设置。1:MyWidget::MyWidget(QWidget *parent)2:: QWidget(parent)3:{4:setWindowTitle(tr(Context Menu Show 2))5:setContextMenuPolicy(Qt::DefaultContextMenu)//其实不用设置,默认就是这个值6:}7:8:9:voidMyWidget::contextMenuEvent(QContextMenuEvent *event)10:{11:QMenu *menu =newQMenu(this)12:menu-addAction(newQAction(tr(&Open), menu))13:menu-addAction(newQAction(QIcon(:/images/mark.png), tr(&Mark), menu))14:menu-addAction(newQAction(tr(&Quit), menu))15:menu-move(cursor().pos())//让菜单显示的位置在鼠标的坐标上16:menu-show()17:}效果:上面直接是在 contextMenuEvent 函数体里面 new 了个菜单和一些菜单项,这是为了演示。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)