9

I have an application where I generate menu items, and I want to set the visibility of a particular sub-menu.

I tried using setVisibility(False), but this did not work. setVisibility() works for menu items, but not for sub-menus in QMenus.

Have a look at the code snippet below:

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.menu = QtGui.QMenu()
        self.actio1 = QtGui.QAction('One', self)
        self.actio2 = QtGui.QAction('Two', self)
        self.menu.addAction(self.actio1)
        self.menu.addAction(self.actio2)
        self.actio1.setVisible(False)
        self.submenu = QtGui.QMenu('submenu', self)
        self.submenu.addAction('sub one')
        self.submenu.addAction('sub two')
        self.menu.addMenu(self.submenu)        
        self.submenu2 = QtGui.QMenu('submenu 2', self)
        self.submenu2.addAction('sub 2 one')
        self.submenu2.addAction('sub 2 two')
        self.menu.addMenu(self.submenu2)        
        self.submenu2.setVisible(False)
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.menu)
        self.setLayout(layout)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

In the above example, I can hide the menu item named "One", but not the sub-menu named "submenu 2"

Can anyone give me an idea...

ekhumoro
  • 98,079
  • 17
  • 183
  • 279
Rao
  • 2,504
  • 12
  • 46
  • 64

1 Answers1

18

You very nearly had it;

Instead of this:

self.submenu2.setVisible(False)

You want this:

self.submenu2.menuAction().setVisible(False)
will
  • 8,940
  • 6
  • 40
  • 63
  • @PBLNarasimhaRao don't mention it – will Dec 04 '12 at 13:08
  • 2
    This works great in C++ QT too: MySubMenu->menuAction()->setVisible(true); Top google hit says it can't be done, so I thought I would share this here. No need to delete submenus and re-add them, which can cause a crash on osx. – Marcus10110 Apr 02 '13 at 02:12
  • 2
    @Marcus10110 - Yah, swapping the `.`s and `->`s between PyQt/PySide and Qt *pretty much* ubiquitously works. – will Apr 06 '13 at 18:57
  • I'm on OS X and my menu is automaticlly moved to the system's menu bar. I tried to both hide a submenu or mark it as disabled; I tried `MySubMenu->menuAction()->setEnabled(false);`, `MySubMenu->menuAction()->setVisible(false);`, `MySubMenu->menuAction()->hide();` and even `MySubMenu->menuAction()->clear();` but none of these made any change in the submenu's appearance. The only thing that worked was `MyMenu->removeAction(MySubMenu->menuAction());`. Hopefully this saves someone else some time and frustration :) – waldyrious Dec 28 '16 at 10:22