Skip to content

Instantly share code, notes, and snippets.

@cestrand
Created August 15, 2015 20:52
Show Gist options
  • Save cestrand/4173c18157f09619d239 to your computer and use it in GitHub Desktop.
Save cestrand/4173c18157f09619d239 to your computer and use it in GitHub Desktop.
Qt - custom context menu
#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
}
}
}
#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