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()
2
  • 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
    Commented Dec 3, 2012 at 16:15
  • @andytilia: you are right. I edited the old questions too.
    – Heisenbug
    Commented Dec 3, 2012 at 16:19

2 Answers 2

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

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:

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.