PDA

View Full Version : QMenu with a additional QPushButton



seux
3rd June 2011, 11:29
Hello,
I also asked this question in another forum, but I haven't got a satisfying answer. I have a simple QMenu with several items. For a few of them I want to add an additional QPushButton to the right side to open an options dialog.

Like in this picture (from Silo 2.2 which also uses Qt):
http://img40.imageshack.us/img40/7707/twobuttonmenu.jpg

How can I achieve this?

mvuori
3rd June 2011, 12:53
I would subclass QMenu, and in the paintEvent of the customised class try to figure out the right place for the buttons and display them.

Santosh Reddy
4th June 2011, 00:12
You can use QWidgetAction class and subclass it it add you own widget to you menu actions.

Like this, implement a custom action PushButtonAction


class PushButtonAction : public QWidgetAction
{
public:
explicit PushButtonAction(const QString& action_text, QObject* parent = 0);
virtual ~PushButtonAction();

private:
QString text;
};

PushButtonAction::PushButtonAction(const QString& action_text, QObject* parent)
: QWidgetAction(parent)
, text(action_text)
{
QWidget* widget = new QWidget();
QHBoxLayout* layout = new QHBoxLayout();

layout->addWidget(new QLabel(text));
layout->addWidget(new QPushButton("Open Dialog"));
widget->setLayout(layout);

setDefaultWidget(widget);
}


and while creating menu



menu->addAction(tr("Action&1"));
menu->addAction(tr("Action&2"));
menu->addSeparator();
menu->addAction(new PushButtonAction("My Action"));
menu->addAction(tr("Action&3"));
menu->addSeparator();
menu->addAction(tr("Action&4"));
menu->addAction(tr("Action&5"));



There is a problem with this method, you will have to sacrifice the QAction default features, like checkable, icon, selection highlight, mouse hove, etc.. all these have to be reimplemented in your custom widget again. If you plan to use all custom actions in your menu, then it not a bad idea to implement those.

wysota
4th June 2011, 06:25
I wouldn't implement something like that as a QMenu. More likely as a widget, be it a custom one based on QAction (to be compliant with QMenu approach) or simply a QTreeWidget/QTableWidget. Menus have a well defined and well known behaviour and trying to change that behaviour hits the user experience and intuition of your application.