How can I toggle layer visibility in QGIS via Python API?
2 Answers
This is from the QGIS docs, if you are running QGIS => 1.5
from PyQt4 import QtCore, QtGui
from qgis import core, gui
i = qgis.utils.iface
# load a georeferenced raster layer
loadedLayer = i.addRasterLayer('c:\\data\\a_map.png')
# get legend
legend = i.legendInterface()
# check current visibility
legend.isLayerVisible(loadedLayer)
# set visibility off
legend.setLayerVisible(loadedLayer, False)
# and on again!
legend.setLayerVisible(loadedLayer, True)
I guess you would just swap out loadedLayer = i.addRasterLayer('c:\\data\\a_map.png')
with the layer that you want to hide, which you could get using something like:
QgsMapLayerRegistry.instance().mapLayer(QString theLayerId)
The accepted answer is not available for QGIS3. In QGIS3, I use the code below:
QgsProject.instance().layerTreeRoot().findLayer(lyr.id()).setItemVisibilityChecked(False)
Also, we can toggle on and off all the layers by:
visible = True # or False
root = QgsProject.instance().layerTreeRoot()
allLayers = root.layerOrder()
for layer in allLayers:
root.findLayer(layer.id()).setItemVisibilityChecked(visible)
-
Your first code block isn't a toggle, but explicitly sets the target layer invisible.– LegatoMar 25, 2020 at 4:49
-