I am trying to create button that change visibility of grouped layers. When person click button all layers inside group is hidden when is clicked again all layers are visible.

So far i know how to hide layers and set them visible in two separate buttons. But i cannot add to function inside one button.

     #connect to Hide_int button that hide intensity rasters

     #connect to Hide_img button that hide img rasters

    def hideint(self):          
        self.maps_treeview = QTreeView()            
        print "Connected"            

    def hideimg(self):            
        print "Connected"            

I am using Qgis 2.16. Can you help me?

2 Answers 2


You could use something like the following which checks:

  • If the group is either unchecked or partially checked then check it
  • If the group is checked, uncheck it

Here is the code tested in QGIS 2.18.2:

def show_hide_group(self):
    group = QgsProject.instance().layerTreeRoot().findGroup('Int')
    # 0 = Unchecked; 1 = Partially checked; 2 = Checked
    if group.isVisible() in (0, 1):


You might find a toggle button handy. See this simple plugin for an example.

icon = QIcon()
icon.addFile( ":/plugins/myPlugin/iconOff.png", state=QIcon.Off )
icon.addFile( ":/plugins/myPlugin/iconOn.png", state=QIcon.On )
self.action = QAction( icon, u"Toggle group visibility", self.iface.mainWindow() )
self.action.toggled.connect( self.run )
self.action.setCheckable( True )

Now, if the button is checked do something, if it's unchecked do something else.

def run( self, checked ):
    if checked:
        # Hide the group    
        # Show the group

If you used the Plugin Builder, you can achieve it by setting checkable=True for the action. See How to check if plugin icon is toggled?

How to set shortcuts has been already answered in GIS.SE. For instance: How to enable a keyboard shortcut for a plugin

  • 1
    +1, I just implemented the change of the png image file when the icon is toggled. Couldn't find any other example of this anywhere so thanks for including that in your answer :)
    – Joseph
    Commented Mar 9, 2017 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.