4

How should one migrate code using QgsMapCanvasLayer to set layer visibility?

The QGIS3 API break page didn't say that QgsMapCanvasLayer is removed or replaced by another class. Yet, it is not listed in the API page either.

For qgis 2 code to set layer visibility as follows:

ml = QgsMapCanvasLayer(lyr)
ml.setVisible(False)

Does it require certain importS in QGIS3 or should it be replaced by something else?

tinlyx
  • 11,057
  • 18
  • 71
  • 119

3 Answers3

16

Just for the record, I had to turn to a different class and member function to set the visibility of a layer lyr in QGIS 3:

QgsProject.instance().layerTreeRoot().findLayer(lyr.id()).setItemVisibilityChecked(False)

This is based on searching/researching the breaking change page:

QgsLayerTreeGroup

setVisible() is replaced by QgsLayerTreeNode::setItemVisibilityChecked()

There might be other ways, but this is what worked for me.

tinlyx
  • 11,057
  • 18
  • 71
  • 119
  • the 'lyr' part doesn't work in a loop. Any idea why? Trying to toggle visibility to select while rendering and saving as *.png – Leo Feb 04 '20 at 05:38
3

The accepted answer is right and I simply want to mention that we can toggle on and off all the layers by:

bool = True # or False
root = QgsProject.instance().layerTreeRoot()
allLayers = root.layerOrder()
for layer in allLayers:
    root.findLayer(layer.id()).setItemVisibilityChecked(bool)
Zac
  • 517
  • 3
  • 10
1

This is a sample code :

from PyQt5.QtWidgets import QDialog
from qgis.core import *
from qgis.gui import *

new_dialog = QDialog()
new_dialog.resize(800, 600)

map_canvas = QgsMapCanvas(new_dialog)
map_canvas.setMinimumSize(800, 600)

layers =  QgsProject.instance().mapLayers()
map_canvas_layer_list = [l for l in layers.values()]
map_canvas.setLayers(map_canvas_layer_list)
map_canvas.setExtent(iface.mapCanvas().extent())

new_dialog.show()

If read the api break documentation,you can see that you need call setLayers() in a QgsMapCanvasclass.

based in this sample for QGIS 2

regards

Fran Raga
  • 7,838
  • 3
  • 26
  • 47