[GIS] Finding the children name of menubar in QGIS Python

context menupyqgis

I have try the code in Finding name of QGIS toolbar in Python? and Name of children of toolbar in QGIS python and how to disable? to show the children name of menuBar. But, get error. The children name of menuBar are : Project, Edit, View, Layer, Settings, Plugins, Vector, Raster, Database, Web, Processing, and Help.

I have input the code :

from PyQt4.QtGui import QToolBar, QDockWidget, QMenuBar
for x in iface.mainWindow().findChildren(QMenuBar):
    print x.objectName()

until here, it is work. The output is menubar. When I type the code :

for icon in iface.menubar().actions(): 
    print icon.objectName()

It gives error : AttributeError: 'QgisInterface' object has no attribute 'menubar'.

To test the name is true, I want to remove many of children name. For example, I want to remove Edit, View, Layer, and Settings. So, how the code in python?

Best Answer

It's correct because u'menubar' is only a name; not an object. Your object is x (specifically a QMenuBar object) and it has effectively an 'actions' method. So, you can do:

from PyQt4.QtGui import QToolBar, QDockWidget, QMenuBar

for x in iface.mainWindow().findChildren(QMenuBar):
    print x.objectName() #redundant because there is only one menubar

for item in x.actions():
    print item

and it's printed:

menubar
<PyQt4.QtGui.QAction object at 0x90baa1dc>
<PyQt4.QtGui.QAction object at 0x90baa53c>
<PyQt4.QtGui.QAction object at 0x90baa584>
<PyQt4.QtGui.QAction object at 0x90baa5cc>
<PyQt4.QtGui.QAction object at 0x90baa614>
<PyQt4.QtGui.QAction object at 0x90baa65c>
<PyQt4.QtGui.QAction object at 0x90baa6a4>
<PyQt4.QtGui.QAction object at 0x90baa6ec>
<PyQt4.QtGui.QAction object at 0x90baa734>
<PyQt4.QtGui.QAction object at 0x90baa77c>
<PyQt4.QtGui.QAction object at 0x90baa7c4>
<PyQt4.QtGui.QAction object at 0x90fdc6a4>

Each one of 12 objects is a QAction object; not a QIcon object. If you want icon name's then:

for i, item in enumerate(x.actions()):
    print i+1, 'name: ', item.icon().name()

but nothing it's printed as 'name' because there is not any icon associated to twelve Menu Bar items.

enter image description here

Related Question