Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide a sub-menu in QMenu

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...

like image 553
Rao Avatar asked Dec 04 '12 12:12

Rao


People also ask

How do I hide a menu in Qt?

and: ui->menuHelp->menuAction()->setVisible(false);

What is sub menu in VB?

A submenu is a secondary menu that appears in another menu. A submenu can be identified by the arrow that follows its name.

How do I add menu bar to QT?

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);


1 Answers

You very nearly had it;

Instead of this:

self.submenu2.setVisible(False)

You want this:

self.submenu2.menuAction().setVisible(False)
like image 109
will Avatar answered Sep 30 '22 12:09

will