How to toggle layer visibility in QGIS using Python?

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)

Tags:

Python

Qgis