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.

- 2,804
- 1
- 19
- 21
-
2You could add to your answer that `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. – Luc Touraille Feb 29 '12 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. – MSalters Mar 01 '12 at 09:09
-
2Hahaha, I had to make sure I wasn't grabbing a seperator...lol – Chef Pharaoh Feb 27 '13 at 21:00
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);

- 4,949
- 2
- 19
- 28
-
My action is not appearing under `ui->` nor under `ui->mainToolBar` (which is where it appears on UI). Where else should it be? I'm using Qt Creator 4.8.2 on Debian 10. – Rodrigo Apr 18 '21 at 02:54