Tuesday, 14 August 2018

qgis 3 - Grouping layers using PyQGIS makes them not visible on canvas?



I've tried using the information in the following posts in order to group layers in PyQGIS (Qgis 3)



I know the second post is for QGIS 2, but I assumed that by using QgsProject in place of QgsMapLayerRegistry, things might work similarly. However all methods have the same problem. When I put even a single layer in a group (using the python code shown below), the layer shows up in the Layers Sidebar in QGIS but it is not visible on the canvas. The interesting thing is that when I right click on the layer in the Layer Sidebar and select Properties, the raster I want to see shows up properly in the thumbnail image at the bottom of the Style tab. When I add the raster to QGIS the normal way (i.e. not using Layer Trees), it shows up exactly as expected. I was wondering if anyone had any idea what might be going on.


Method 1:


    raster_layer = QgsRasterLayer(filename, name)
QgsProject.instance().addMapLayer(raster_layer)
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup(group_name)
layer = root.findLayer(raster_layer.id())
layer2 = layer.clone()

group.addChildNode(layer2)
root.removeChildNode(layer)

Method 2:


    raster_layer = QgsRasterLayer(filename, name)
group = root.addGroup(group_name)
QgsProject.instance().addMapLayer(raster_layer, False)

layer = QgsLayerTreeLayer(raster_layer)
group.insertChildNode(0, layer)


The only method that works to successfully add the raster to the QGIS canvas is simply:


    raster_layer = QgsRasterLayer(filename, name)
QgsProject.instance().addMapLayer(raster_layer)

In fact even when I don't try to add the raster to a group, but try to add it to the root itself using any other method besides addMapLayer(), the raster doesn't show on the canvas.


For example:


    raster_layer = QgsRasterLayer(filename, name)
root = QgsProject.instance().layerTreeRoot()
QgsProject.instance().addMapLayer(raster_layer, False)

root.addLayer(raster_layer)

Or using the example from the third link:


    raster_layer = QgsRasterLayer(filename, name)
QgsProject.instance().addMapLayer(raster_layer, False)
layerTree = iface.layerTreeCanvasBridge().rootGroup()
layerTree.insertChildNode(-1, QgsLayerTreeLayer(raster_layer))

Answer



I'm very embarrassed. The group was showing up on the canvas, just behind a layer that was already there, so I never saw it. There was absolutely no problem with PyQGIS.


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...