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

前端 未结 3 487
独厮守ぢ
独厮守ぢ 2020-12-31 04:49

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 a

相关标签:
3条回答
  • 2020-12-31 04:55

    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);
    
    0 讨论(0)
  • 2020-12-31 05:05

    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

    0 讨论(0)
  • 2020-12-31 05:11

    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

    0 讨论(0)
提交回复
热议问题