1

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))
  • Have you tried using raster_layer.triggerRepaint() or iface.mapCanvas().refresh()? – Joseph Jan 24 at 11:57
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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