本篇以QPushButton为例实现添加右键菜单,使用DefaultContextMenu方式进行实现。
大体思路和前面两篇添加菜单的方式还是差不多的。虽然是以QPushButton为例进行实现,但是对于所有QWidget添加右键菜单都是适合的。
不同的是菜单策略,DefaultContextMenu需要继承contextMenuEvent事件,
void contextMenuEvent(QContextMenuEvent *event);设置使用菜单的策略是
setContextMenuPolicy(Qt::DefaultContextMenu);然后实现 contextMenuEvent事件
void DefaultMenu::contextMenuEvent(QContextMenuEvent *event) { __super::contextMenuEvent(event); m_menu->exec(QCursor::pos()); }因为QMenu肯定是要显示在光标处,所以可以使用QCursor::pos()来获取光标的当前位置。
实现后的效果如下:
#ifndef DEFAULTMENU_H #define DEFAULTMENU_H #include <QtWidgets/QPushButton> #include <QAction> #include <QMenu> #include <QDebug> class DefaultMenu : public QPushButton { Q_OBJECT public: DefaultMenu(QWidget *parent = 0); ~DefaultMenu(); void contextMenuEvent(QContextMenuEvent *event); protected slots: void actionOneSlot(); void actionTwoSlot(); void actionThreeSlot(); private: QMenu *m_menu; QAction *m_actionOne; QAction *m_actionTwo; QAction *m_actionThree; }; #endif // DEFAULTMENU_H
#include "defaultmenu.h" DefaultMenu::DefaultMenu(QWidget *parent) : QPushButton(parent) { setContextMenuPolicy(Qt::DefaultContextMenu); m_menu = new QMenu(this); m_actionOne = new QAction(this); m_actionTwo = new QAction(this); m_actionThree = new QAction(this); m_actionOne->setText("ActionOne"); m_actionTwo->setText("ActionTwo"); m_actionThree->setText("ActionThree"); m_menu->addAction(m_actionOne); m_menu->addAction(m_actionTwo); m_menu->addAction(m_actionThree); connect(m_actionOne, SIGNAL(triggered()), this, SLOT(actionOneSlot())); connect(m_actionTwo, SIGNAL(triggered()), this, SLOT(actionTwoSlot())); connect(m_actionThree, SIGNAL(triggered()), this, SLOT(actionThreeSlot())); } DefaultMenu::~DefaultMenu() { } void DefaultMenu::actionOneSlot() { qDebug() << "actionOne"; } void DefaultMenu::actionTwoSlot() { qDebug() << "actionTwo"; } void DefaultMenu::actionThreeSlot() { qDebug() << "actionThree"; } void DefaultMenu::contextMenuEvent(QContextMenuEvent *event) { __super::contextMenuEvent(event); m_menu->exec(QCursor::pos()); }
#include "defaultmenu.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; DefaultMenu b(&w); b.setText("Button"); w.show(); return a.exec(); }
源码下载:http://download.csdn.net/detail/u011417605/9466459
本文地址:http://blog.csdn.net/u011417605/article/details/50930698
交流QQ:1245178753