5

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
     self.dockwidget.Hide_int.clicked.connect(self.hideint)

     #connect to Hide_img button that hide img rasters
     self.dockwidget.Hide_img.clicked.connect(self.hideimg)                

    def hideint(self):          
        self.maps_treeview = QTreeView()            
        QgsProject.instance().layerTreeRoot().findGroup('Int').setVisible(0)            
        print "Connected"            
        pass

    def hideimg(self):            
        QgsProject.instance().layerTreeRoot().findGroup('Int').setVisible(2)
        QgsProject.instance().layerTreeRoot().findGroup('Int').updateChildVisibility()
        print "Connected"            
        pass

I am using Qgis 2.16. Can you help me?

5

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):
        group.setVisible(2)
    else:
        group.setVisible(0)

self.dockwidget.show_hide_pushButton.clicked.connect(self.show_hide_group)
4

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    
    else:
        # 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 Mar 9 '17 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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