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...
and: ui->menuHelp->menuAction()->setVisible(false);
A submenu is a secondary menu that appears in another menu. A submenu can be identified by the arrow that follows its name.
In most main window style applications you would use the menuBar() function provided in QMainWindow, adding QMenus to the menu bar and adding QActions to the pop-up menus. Example (from the Menus example): fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct);
You very nearly had it;
Instead of this:
self.submenu2.setVisible(False)
You want this:
self.submenu2.menuAction().setVisible(False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With