在Qt 4.7中,如何将弹出菜单添加到QToolbar按钮?

问题描述:

我是Qt的新手,目前正在使用Qt Creator和原始C ++代码.通过将QAction对象添加到这两者中,我设法使一些简单的功能起作用,包括菜单和工具栏.但是我遇到了一些困难:

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:

我想做的是有一个带有子菜单的菜单选项,例如新增,带有子菜单,其中包含项目组合,并在QToolbar上重复该菜单.我已经在菜单中对其进行了管理:新建为QMenu,子菜单项为QAction对象.我看不到如何使其在工具栏中工作,例如一个新按钮,单击该按钮将运行默认" QAction(例如第一个子菜单项),但右侧的菜单按钮较小,提供所有其他选项.我想这类似于Office工具栏上的撤消/重做"按钮.

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.

我相信QToolButton 窗口小部件可以很好地满足您的需求,请查看下面的示例是否适合您:

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);

希望这会有所帮助