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...
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
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()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With