Setting layer visibility in QGIS Python API?

For QGIS 3, you have to use: QgsProject.instance().layerTreeRoot().findLayer(layer_id).setItemVisibilityChecked(False)

or to be safe

node = QgsProject.instance().layerTreeRoot().findLayer(layer_id)
if node:
  node.setItemVisibilityChecked(False)

Reading the documentation, findLayer accepts both the layer itself or the layer ID as a string.


At the moment (QGIS 2.x) (and I know it's a bit gross) but you also have to update the layer set on the canvas to update the layer state change

canvas.setLayerSet([ml2, ml])

This will also control the render order. m1 will reneder first then ml2 on top of it.