#ifndef QMENUBUTTON_H #define QMENUBUTTON_H #include <QToolButton> class QMenu; class QMenuButton : public QToolButton { Q_OBJECT public: explicit QMenuButton(QWidget *parent = 0); QMenu * getmenu(); QMenu * menu; signals: public slots: void popupmenu(); }; #endif // QMENUBUTTON_H
#include "qmenubutton.h" #include <QMenu> #include<QRect> QMenuButton::QMenuButton(QWidget *parent) : QToolButton(parent) { menu = new QMenu(this); connect(this,SIGNAL(clicked()),this,SLOT(popupmenu()));//点击按钮就弹出菜单 } QMenu *QMenuButton::getmenu() { return menu; } void QMenuButton::popupmenu() { QPoint pos; //获取按键菜单的坐标 // int x = pos.x(); int y = pos.y(); // pos.setX(x + this->geometry().width()/2);//也可以改变出现菜单的窗口的x位置 pos.setY(y-this->geometry().height()); //返回菜单下面的action不管有没被选中,可以算一个小事件循环 //里面参数的意思是在哪个坐标弹出菜单,这里将自定义的pop按键的坐标作参考,并在其下面弹出菜单 menu->exec(this->mapToGlobal(pos)); }
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; }; #endif // WIDGET_H
#include "widget.h" #include "ui_widget.h" #include<QMenu> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QMenu * menu = ui->MenuButton->getmenu();//获得菜单,并向上面添加菜单 QAction* ToTop =menu->addAction("toTop");//一级菜单 //ToTop->setIcon(QIcon(":/searchwindow/searchwindow/topon_normal.png")); 为ToTop菜单添加图片标识 // connect(ToTop, SIGNAL(triggered()), this, SLOT(on_toTopBtn_clicked()));添加事件,当单击ToTop时,产生相应的事件 QMenu *fontMenu=menu->addMenu("Font"); QAction* FontSize1 = fontMenu->addAction("small");//二级菜单 QAction* FontSize2 = fontMenu->addAction("middle"); QAction* FontSize3 = fontMenu->addAction("large"); } Widget::~Widget() { delete ui; }
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
原文地址:http://blog.csdn.net/tengweitw/article/details/45099867