0

I'm developing a QGIS plugin, to load PostGIS layers in QGIS.

I'd like to :

  • Create a layer group
  • Add several layers in this group.

The code below adds the layer to the canvas, and in the layer panel. Only there is no interaction between the layer panel and the map.

However, if I close and reopen my project, the layer interacts correctly with the map.

I noticed that if I took the layer out of the group, then the map interacts correctly with the layer panel.

I think I'm missing an action to refresh the layer panel, or something like that. Does anyone have an idea?

uri = QgsDataSourceUri()
uri.setConnection(host, port, database, user, password)
layer = QgsVectorLayer(uri.uri(), tablename, 'postgres')

root = QgsProject.instance().layerTreeRoot()
mygroup = root.insertGroup(0, 'MyGroup')

QgsProject.instance().addMapLayer(layer, False) #Add Map layer
root.findGroup(mygroup ).addLayer(layer) #Add layer in group

iface.reloadConnections() #refresh
3
  • You can try iface.mapCanvas().refresh() and/or QgsProject.instance().reloadAllLayers()
    – Matt
    Mar 24, 2023 at 15:15
  • 2
    You create layer "layer", but add to map "new_layer" - ...addMapLayer(new_layer, False) ...
    – RainForest
    Mar 24, 2023 at 19:31
  • I tried iface.mapCanvas().refresh() and QgsProject.instance().reloadAllLayers(), but I have the same issue. I corrected the code snippet, with the right layer variable "layer" (it was just a copy / paste error)
    – sallib
    Mar 27, 2023 at 7:54

1 Answer 1

1

I suspect that your problem is this line:

root.findGroup(mygroup ).addLayer(layer) #Add layer in group

The findGroup() method takes a string argument (the group name), but you are passing it a QgsLayerTreeGroup object (returned from the insertGroup() method and stored in your mygroup variable).

Since you already have a QgsLayerTreeGroup object, all you have to do is:

QgsProject.instance().addMapLayer(layer, False)
mygroup.addLayer(layer)

So:

uri = QgsDataSourceUri()
uri.setConnection(host, port, database, user, password)
layer = QgsVectorLayer(uri.uri(), tablename, 'postgres')

root = QgsProject.instance().layerTreeRoot()
mygroup = root.insertGroup(0, 'MyGroup')

QgsProject.instance().addMapLayer(layer, False) #Add Map layer
mygroup.addLayer(layer) #Add layer in group
1
  • Sadly, it doesn't change anything :( All layers that are not in a group react well. But in groups, they don't respond properly until the project has been closed and reopened.
    – sallib
    Aug 25, 2023 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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