Created
August 15, 2015 20:52
-
-
Save cestrand/4173c18157f09619d239 to your computer and use it in GitHub Desktop.
Qt - custom context menu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QMenu> | |
#include <QAction> | |
MyWidget::MyWidget(QWidget* parent) : QWidget(parent) | |
{ | |
setContextMenuPolicy(Qt::CustomContextMenu); | |
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuShow(QPoint))); | |
} | |
void MyWidget::customContextMenuShow(const QPoint& pos) | |
{ | |
QPoint globalPos = mapToGlobal(pos); | |
QMenu menu; | |
QAction* action_firstAction = menu.addAction( | |
QIcon(), | |
QString("First action") | |
); | |
menu.addSeparator(); | |
QAction* action_secondAction = menu.addAction( | |
QIcon(), | |
QString("Second action") | |
); | |
QAction* selected_action = menu.exec(globalPos); | |
if(selected_action) { | |
if(selected_action == action_firstAction) | |
{ | |
// do something for first action | |
} | |
else if(selected_action == action_secondAction) | |
{ | |
// do something for second action | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef MYWIDGET_H | |
#define MYWIDGET_H | |
#include <QWidget> | |
class MyWidget : public QWidget | |
{ | |
Q_OBJECT | |
public: | |
explicit MyWidget(QWidget* parent = 0); | |
public slots: | |
void customContextMenuShow(const QPoint& pos); | |
}; | |
#endif // MYWIDGET_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment