[GIS] How to hide/show QGisVectorLayer from Python code

pythonqgisqgis-plugins

Once created a layer, how can I hide/show it? I can enable/disable rendering of a specific layer by selecting the checkbox through QGIS, but I need to do it programmatically from python code.

How can I show/hide(not remove) a label from python code?

I'm looking for something like:

aLayer = self.addVectorLayer(uri.uri(), layerName, self.dbConn.getProviderName())
aLayer.Hide()
....
aLayer.Show()

Best Answer

You can control the layer visibility through the legend object. Here it is, using your sample code above:

aLayer = self.addVectorLayer(uri.uri(), layerName, self.dbConn.getProviderName())
legend = self.legendInterface()  # access the legend
legend.setLayerVisible(aLayer, False)  # hide the layer
# do something else
legend.setLayerVisible(aLayer, True)  # show the layer

# maybe later I want to check if the layer is visible
print legend.isLayerVisible(aLayer)

Here's the documentation for legendInterface: http://qgis.org/api/classQgsLegendInterface.html

Good luck!