Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - Pop up menu

Tags:

qt

popup

menu

I have added a label as an image(icon) to a widget in Qt. I want to display a pop-up menu when the user clicks (left or right click) on the label. How can I achieve this ? Please help...

like image 274
Maddy Avatar asked Jan 24 '11 05:01

Maddy


2 Answers

You'll want to set the ContextMenuPolicy of the widget, then connect the customContextMenuRequested event to some slot which will display the menu.

See: Qt and context menu

like image 68
Cam Avatar answered Oct 22 '22 00:10

Cam


If you want to display a context menu whenever the label is clicked (with any mouse button), I guess you'll have to implement your own Label class, inheriting QLabel and handling the popup menu by yourself in case of a mouse event.

Here is a very simplified (but working) version :

class Label : public QLabel
{
public:
    Label(QWidget* pParent=0, Qt::WindowFlags f=0) : QLabel(pParent, f) {};
    Label(const QString& text, QWidget* pParent = 0, Qt::WindowFlags f = 0) : QLabel(text, pParent, f){};

protected :
    virtual void mouseReleaseEvent ( QMouseEvent * ev ) {
        QMenu MyMenu(this);
        MyMenu.addActions(this->actions());
        MyMenu.exec(ev->globalPos());
    }
};

This specialized Label class will display in the popup menu all actions added to it.

Let's say the main window of your application is called MainFrm and is displaying the label (label. Here is how the constructor would look :

MainFrm::MainFrm(QWidget *parent) : MainFrm(parent), ui(new Ui::MainFrm)
{
    ui->setupUi(this);

    QAction* pAction1 = new QAction("foo", ui->label);
    QAction* pAction2 = new QAction("bar", ui->label);
    QAction* pAction3 = new QAction("test", ui->label);
    ui->label->addAction(pAction1);
    ui->label->addAction(pAction2);
    ui->label->addAction(pAction3);
    connect(pAction1, SIGNAL(triggered()), this, SLOT(onAction1()));
    connect(pAction2, SIGNAL(triggered()), this, SLOT(onAction2()));
    connect(pAction3, SIGNAL(triggered()), this, SLOT(onAction3()));
}
like image 33
Jérôme Avatar answered Oct 21 '22 22:10

Jérôme