Qt - Pop up menu

廉价感情. 提交于 2019-12-21 12:33:55

问题


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


回答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




回答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()));
}



回答3:


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()));


来源:https://stackoverflow.com/questions/4778961/qt-pop-up-menu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!