我在Qt中的一个小部件上添加了一个标签作为图像(图标)。 我想要在用户单击(左键或右键)标签时显示弹出菜单。 我该如何实现?请帮忙......
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()));
}
#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()));