Sunday, 23 October 2016

pyqgis - Set layer visibility using QgsMapCanvasLayer in QGIS 3?


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?



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...