[GIS] How to customize the QGIS GUI using Python

guipyqgispythonqgisqgis-plugins

Is it possible to hide/remove/customize the default UI of QGIS from a Python plugin?

I want to add my own menus and toolbars and remove some included by default in QGIS.

If it's possible, which reference should I use?

Best Answer

Yes, it's possible to customize the QGIS UI from a Python plugin by both adding your own toolbars and menus as well as removing/hiding QGIS toolbars and menus.

These would be the code snippets for each situation:

  1. Adding a toolbar:

    # Add a custom toolbar
    self.toolbar = self.iface.addToolBar( "My tools" )
    self.toolbar.setObjectName( "My tools" )
    self.toolbar.addAction( self.action )
    
  2. Removing a QGIS toolbar:

    # Remove a QGIS toolbar (e.g., the File toolbar)
    fileToolBar = self.iface.fileToolBar()
    self.iface.mainWindow().removeToolBar( fileToolBar )
    
  3. Adding a menu:

    # Add a custom menu
    self.menu = QMenu( "&My tools", self.iface.mainWindow().menuBar() )
    self.menu.setObjectName( "&My tools" )
    actions = self.iface.mainWindow().menuBar().actions()
    lastAction = actions[-1]
    self.iface.mainWindow().menuBar().insertMenu( lastAction, self.menu )
    self.menu.addAction( self.action )
    
  4. Removing a QGIS menu:

    # Remove a QGIS menu (e.g., the Edit menu)
    editMenu = self.iface.editMenu()
    editMenu.menuAction().setVisible( False )
    

You can append such code to the initGui() method of your plugin. I assumed you have an action created in such method, as any plugin has.

You can see these code snippets implemented in a test plugin that I've created and published here. In the README file you find instructions for both installing and using it.


Note: You can get a reference of QGIS menus and toolbars from Python by using methods exposed by iface. A list of such methods can be found in the QGIS docs.

Related Question