Qt - popup menu

I added a shortcut as an image (icon) to the widget in Qt. I want to display a popup menu when a user clicks (left or right click) on a shortcut. How can i achieve this? Please, help...

+6
source share
3 answers

You need to install the ContextMenuPolicywidget, then connect the event customContextMenuRequestedto some slot that displays the menu.

See: Qt and the context menu

+6
source

, ( ), , Label, QLabel .

( ) :

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

Label , .

, MainFrm (Label). :

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()));
}
+4

, " ", " ".

QToolButton QSS .

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

All Articles