I'm building a small program in Qt with menu bars (menuBar) using C++ and I would like to know how to gray out (eg. disable) an item of the menu when a certain variable is activated. Is it possible?
2 Answers
If you know an index of the corresponding QAction :
QMenu::actions.at(i).setEnabled(false);
P.S. As kindly prompted below, setEnabled(bool)
and setDisabled(bool)
are slots (so is toggle()
), so they can be connected to a signal indicating a need to change the availability of the action.
-
2You could add to your answer that
setEnabled(bool)
andsetDisabled(bool)
are slots (so istoggle()
), so they can be connected to a signal indicating a need to change the availability of the action. Feb 29, 2012 at 22:26 -
3If the variable changes frequently (more often than the menu is shown), it may be wise to toggle it only in response to
signal: QMenu::aboutToShow()
; no point in changing something that's invisible anyway.– MSaltersMar 1, 2012 at 9:09 -
2
Looking for the index of the action is not necessarily convenient. If you have built the interface with QtCreator's form editor then you will have an action for each menu item. Their names are based on the text that you first give to the actions. For example if you interactively enter a menu item with title Foo Bar then an action named actionFoo_Bar is created for you. Just type ui->action in the code editor and watch what "name completion" QtCreator will propose.
In such a case I would consider a call like this:
ui->actionFoo_Bar.setEnabled(false);
You can even make the menu item disappear with
ui->actionFoo_Bar.setVisible(false);
-
My action is not appearing under
ui->
nor underui->mainToolBar
(which is where it appears on UI). Where else should it be? I'm using Qt Creator 4.8.2 on Debian 10.– RodrigoApr 18, 2021 at 2:54