开发者

In Qt 4.7, how can a pop-up menu be added to a QToolbar button?

I am newbie to Qt and am currently playing about with Qt Creator and raw C++ code. I have managed to get some simple functionality working, including a menu and 开发者_开发问答toolbar by adding QAction objects to both. However I am having some difficulty:

What I would like to do is have a menu option which has a submenu, e.g. New, with a submenu with a couplwe of items, and duplicate this on the QToolbar. I have managed it in the menu: New as a QMenu, and submenu items as QAction objects. I cannot see how to get this to work in the toolbar, e.g. a New button which, when clicked, would run the "default" QAction (such as the first submenu item), but with a smaller menu button to the right offering all other options. I suppose this is analogous to the Undo/Redo buttons on the Office toolbars.


I believe QToolButton widget should work fine for what you're trying to do, see if and example below would work for you:

QMenu *menu = new QMenu();
QAction *testAction = new QAction("test menu item", this);
menu->addAction(testAction);

QToolButton* toolButton = new QToolButton();
toolButton->setMenu(menu);
toolButton->setPopupMode(QToolButton::InstantPopup);
toolBar->addWidget(toolButton);

hope this helps, regards


serge_gubenco's answer will work, except when the window needs to be resized smaller and Qt tries to put the QToolButton itself in a popup menu. It may be unable do so. See http://doc.qt.io/archives/qt-4.7/qtoolbar.html.

The solution is to use a quick QWidgetAction, as below in a modified snippet.

QMenu *menu = new QMenu();
QAction *testAction = new QAction("test menu item", this);
menu->addAction(testAction);

QToolButton* toolButton = new QToolButton();
toolButton->setMenu(menu);
toolButton->setPopupMode(QToolButton::InstantPopup);

QWidgetAction* toolButtonAction = new QWidgetAction(this);
toolButtonAction->setDefaultWidget(toolButton);

toolBar->addAction(toolButtonAction);


It seems QToolButton already has some sort of submenu, which is set with QToolButton::setPopupMode(ToolButtonPopupMode mode). If I've got you right, that would be a place to start: http://doc.qt.io/archives/qt-4.7/qtoolbutton.html#ToolButtonPopupMode-enum


Try this. In this example it shows how to add a QToolbutton to a menu and attach a function to it. Also the menu itself can be attached another slot.

https://github.com/IsharaPriyadarshana/CustomQTMenu

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜