4

When a layer is added to QGIS, it is ordinarily added to "Layers" panel and "Map Canvas". The same thing happens when a memory layer (loaded/created by QgsVectorLayer) is added using QgsProject.instance().addMapLayer.

layer = QgsVectorLayer("Polygon?crs=EPSG:4326", "Buffer", "memory")
# 
QgsProject.instance().addMapLayer(layer) # after this line, layer is added to both area.

When writing a script step by step, I usually add intermediate layers to control if the script runs correctly. Then I need to remove them manually and repeatedly.

I want a layer which I add to memory to be added to "Map Canvas" only. How can I achieve that? Is it possible to break the connection between "Layers" panel and "Map Canvas".

For example, as shown in the image, I want Buffer layer to appear only in "Map Canvas", but not in "Layers" panel.

enter image description here

3

1 Answer 1

4

I‘ve had the same question for a while and didn't find a proper solution. Thanks to @Germán Carrillo's post and plugin, I found a way. Thank you so much.

Sorry I cannot install an extra plugin at work, so I summarised some snippets from Germán's scripts. It works well for me, hopefully it could be useful to others as well.

If you are interested in the code, please read Germán's link above or go to the plugin github page.

# get the current layer or use a temp layer as @Kadir did above
layer = iface.activeLayer()

ltv = iface.layerTreeView()
model = ltv.model()
root = QgsProject.instance().layerTreeRoot()

index = model.node2index( root.findLayer(layer.id()))
# use True to hide the layer
ltv.setRowHidden( index.row(), index.parent(), True )
ltv.setCurrentIndex( model.node2index( root ) )

You can set the layer to be visible again by

ltv.setRowHidden( index.row(), index.parent(), False )

It can also be remove when it's invisible

QgsProject.instance().removeMapLayer(layer.id())
iface.mapCanvas().refresh()

UPDATE:

Recently, I found QGIS documentation provided a solution to this question and it's almost the same as shown above. Take a look if you like. Go to this link, and search "Hidden node trick" on the page.

1
  • I saw the snippset but it uses the iface wich is not available in a standalone script. I couldn't be able to hide a node without it.
    – SIGIS
    Commented Jun 25, 2021 at 10:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.