Show and hide tool buttons
-
wrote 23 days ago last edited by
A desktop app has several toolbars with different tool buttons. And each tool button is linked to a menu entry.
In a ToolBar Settings dialog, the visibility of the individual tool buttons should be switched on or off (show/hide).
However, you can only activate and deactivate the tool buttons. You can only switch the visibility in the QAction on and off. But then the menu entry also disappears.One solution would be to create another QAction and copy the data of the Menu-QAction into it and link them together. And then assign this to the tool button.
Then you can switch the visibility of the tool button in the dialog on or off (show/hide) and the menu entry remains.Is there an easier way in Qt 6.9 ?
Why is it not possible to switch off the visibility of a tool button?Thanks
Ralf -
wrote 23 days ago last edited by
You'll need to use QWidget *button = toolbar->widgetForAction(action); and then call button->setVisible(false); to hide the button on the toolbar.
-
wrote 22 days ago last edited by
auto action1 = new QAction(tr("Action 1"), this); auto action2 = new QAction(tr("Action 2"), this); action2->setCheckable(true); auto testsMenu = menuBar()->addMenu(tr("Tests")); testsMenu->addAction(action1); testsMenu->addAction(action2); auto testsToolbar = new QToolBar(tr("Tests Toolbar"), this); testsToolbar->setObjectName(QStringLiteral("testsToolbar")); testsToolbar->addAction(action1); testsToolbar->addAction(action2); addToolBar(testsToolbar); auto widget1 = testsToolbar->widgetForAction(action1); widget1->setEnabled(false); // works auto widget2 = testsToolbar->widgetForAction(action2); widget2->setVisible(false); // doesn't work
Thanks for your help but it doesn't work.
-
wrote 22 days ago last edited by
Try calling testsToolbar->update(); after widget2->setVisible(false);. That could help refresh the layout.
-
wrote 21 days ago last edited by
It still doesn't work.
Note: You should use QAction::setVisible() to change the visibility of the widget. Using QWidget::setVisible(), QWidget::show() and QWidget::hide() does not work.
Source: https://doc.qt.io/qt-6/qtoolbar.html#addWidget
That's why I'm currently "cloning" every QAction. The original for the menu, and the clone for the toolbar.
-
wrote 21 days ago last edited by
I also tried it, and it turns out it doesn't work either. When a QToolButton is linked to an action, you can't hide the button if the action is still visible. It's one of those quirky things in the implementation.
I think instead of trying to hide it, you can try using removeAction() and then add or insert it back when needed.
1/6