15

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

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()
Taras
  • 32,823
  • 4
  • 66
  • 137
Heisenbug
  • 893
  • 2
  • 10
  • 23
  • I'm glad you changed the variable name vl (from the similar code sample in an earlier question) to aLayer. It's easy to confuse the lowercase letter l with the digit 1. – andytilia Dec 03 '12 at 16:15
  • @andytilia: you are right. I edited the old questions too. – Heisenbug Dec 03 '12 at 16:19

2 Answers2

11

For QGIS 2 versions

One 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)

For more details, see the documentation for legendInterface: https://api.qgis.org/api/2.18/classQgsLegendInterface.html

Taras
  • 32,823
  • 4
  • 66
  • 137
andytilia
  • 1,825
  • 15
  • 25
1

For QGIS 3 versions

It can be achieved either

since QGIS 3.10

or the setLayerVisible() method of the QgsLayerTreeView class:

from qgis.utils import iface

layer = iface.activeLayer() view = iface.layerTreeView()

view.setLayerVisible(layer, False)

since QGIS 3.0

through the setItemVisibilityChecked() method, that belongs to the QgsLayerTreeNode class:

from qgis.utils import iface
from qgis.core import QgsProject

layer = iface.activeLayer()

node = QgsProject.instance().layerTreeRoot().findLayer(layer.id())

if node.isVisible(): node.setItemVisibilityChecked(False)


References:

Taras
  • 32,823
  • 4
  • 66
  • 137