Qt - Pop up menu

22,117

Solution 1

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

Solution 2

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()));
}
Share:
22,117

Related videos on Youtube

Maddy
Author by

Maddy

Updated on August 22, 2020

Comments

  • Maddy
    Maddy over 3 years

    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...

    • SilverSideDown
      SilverSideDown over 13 years
      What do you want exactly : a pop up menu when contextual menu is requested (right click), or a pop up menu whenever the label is clicked, no matter if it's the left or right button ?

Related