QToolButton を使用する必要があります。次に、ボタンのテキストの代わりにアイコンを設定し、popupmenu プロパティを menubuttonpopup に設定します。これは私のコードです:
//widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QtGui>
Widget::~Widget()
{
delete ui;
}
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
menu = new QMenu(this);
act0 = new QAction("test",this);
act1 = new QAction("test1",this);
act0->setObjectName("act0");
act1->setObjectName("act1");
menu->addAction(act0);
menu->addAction(act1);
ui->toolButton->setMenu(menu);
connect(ui->toolButton,SIGNAL(clicked()),this,SLOT(slotTest()));
connect(act0,SIGNAL(triggered()),this,SLOT(slotTest()));
connect(act1,SIGNAL(triggered()),this,SLOT(slotTest()));
adjustSize();
}
void Widget::slotTest()
{
QToolButton *tbtn = qobject_cast<QToolButton*>(sender());
QAction *act = qobject_cast<QAction*>(sender());
if(tbtn)
{
qDebug() << "event raised by QToolButton: " << tbtn->objectName();
}
if(act)
{
qDebug() << "event raised by QAction: " << act->objectName();
}
}
//widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class QMenu;
class QAction;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void slotTest();
private:
QMenu *menu;
QAction *act0;
QAction *act1;
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.ui:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>53</width>
<height>40</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QToolButton" name="toolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>cerca.png</normaloff>cerca.png</iconset>
</property>
<property name="popupMode">
<enum>QToolButton::MenuButtonPopup</enum>
</property>
</widget>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>