2011-01-24 152 views
5

我已經添加了一個標籤作爲圖像(圖標)到Qt中的一個小部件。 我想在用戶單擊標籤上的(左鍵或右鍵單擊)時顯示彈出式菜單。 我該如何做到這一點?請幫助...Qt - 彈出菜單

+1

你想要什麼確切:一個彈出菜單,當請求上下文菜單(右擊),或一個彈出菜單,只要標籤被點擊時,不管它的左邊或右邊的按鈕? – 2011-01-24 06:34:19

回答

6

您需要設置小部件的​​,然後將customContextMenuRequested事件連接到某個顯示菜單的插槽。

參見:Qt and context menu

4

如果你想顯示每當標籤點擊(與任何鼠標按鈕)的上下文菜單,我想你必須實現自己的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())); 
} 
0

如果標籤是點擊,這在邏輯上是一個「文本按鈕「而不是」 標籤「了。

我會建議使用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()));