Search code examples
c++qtc++11qt4qt5

Show a QMenu in response to right click in a QLabel, possible?


I'm thinking in show a QMenu in response to user click on a QLabel. So I tried:

menu.h

#ifndef MENU_H
#define MENU_H

#include <QMenu>

class Menu : public QMenu
{
    Q_OBJECT
public:
    explicit Menu(QWidget *parent = 0);

signals:

public slots:
};

#endif // MENU_H

menu.cpp

#include "menu.h"

Menu::Menu(QWidget *parent) :
    QMenu(parent)
{
    addAction("Action1");
}

And the code who would supposedly call show the menu:

QLabel *label = new QLabel("...");
m_menu = new Menu;
label->setContextMenuPolicy(Qt::CustomContextMenu);    
connect(label, &QLabel::customContextMenuRequested, m_menu, &Menu::activateWindow);

But it's not working. Where I'm wrong?


Solution

  • Try like this :

    menu.h

    #ifndef MENU_H
    #define MENU_H
    
    #include <QMenu>
    
    class Menu : public QMenu
    {
        Q_OBJECT
    public:
        explicit Menu(QWidget *parent = 0);
    
    signals:
    
    public slots:
    void showMenu(const QPoint &pos);
    };
    
    #endif // MENU_H
    

    menu.cpp

    #include "menu.h"
    
    Menu::Menu(QWidget *parent) :
        QMenu(parent)
    {
        addAction("Action1");
    }
    Menu::showMenu(const QPoint &pos)
    {
        exec(mapToGlobal(pos));
    }
    

    And here your label :

    QLabel *label = new QLabel("...");
    m_menu = new Menu;
    label->setContextMenuPolicy(Qt::CustomContextMenu);    
    connect(label, SIGNAL(customContextMenuRequested(QPoint)), m_menu, SLOT(showMenu(QPoint)));