Reputation: 61
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...
Upvotes: 6
Views: 25378
Reputation: 6623
If a label is clickable, it is logically a "textual button" and not a "label" any more.
I would suggest to use QToolButton instead, and use QSS to make up the toolbutton to a label.
#define SS_TOOLBUTTON_TEXT(_normal, _hover, _disabled) \
"QToolButton" "{" \
"background:transparent" \
"color:" #_normal ";" \
"}" \
"QToolButton:hover" "{" \
"color:" #_hover ";" \
"}" \
"QToolButton:disabled" "{" \
"color:" #_disabled ";" \
"}"
....
QToolButton *b = new QToolButton; {
b->setToolButtonStyle(Qt::ToolButtonTextOnly);
b->setStyleSheet(SS_TOOLBUTTON_TEXT(blue, red, gray));
b->setText(QString("[%1]").arg(tr("menu"));
}
b->setMenu(menu_to_popup);
connect(b, SIGNAL(clicked()), b, SLOT(showMenu()));
Upvotes: 0
Reputation: 27027
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()));
}
Upvotes: 4
Reputation: 709
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
Upvotes: 7