How can I toggle layer visibility in QGIS via Python API?

2 Answers 2


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
# 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:


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:

  • Your first code block isn't a toggle, but explicitly sets the target layer invisible.
    – Legato
    Mar 25, 2020 at 4:49
  • @Legato, use setItemVisibilityChecked(boolean) to toggle the layer
    – Zac
    Apr 15, 2020 at 5:47

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.