I'm trying to add layer in group on QGIS using those code:
qgis_groups = QgsProject.instance().layerTreeRoot()
path = QgsProject.instance().readPath("./")
operators_path = join(path, 'RSX')
operators_content = [item for item in os.listdir(operators_path) if isdir(join(operators_path, item))]
shp = qgis_groups.findGroup('SHP')
for item in operators_content:
shp_path = join(operators_path, item, 'SHP')
for shp_file in glob.glob(join(shp_path, '*.shp')):
layer_name = basename(shp_file).replace(".shp", "")
layer = QgsVectorLayer(shp_file, layer_name, "ogr")
shp.addLayer(layer)
the layers loaded on QGIS become None
only the last layer is worked, So I tried to call addLayer
outside for
It worked but the previous layer become None
again. Then I tried with inserLayer(i, layer)
but same problem.
Anyone has an idea about that?
Answer
It does seem like very strange behaviour and I would assume it's a bug (you should report it to get confirmation). A possible workaround could be to:
- Add the layer to the group;
- Add it to the map registry but keep it hidden;
- Set this as the active layer so that when the next layer is added, it will be added to the same group because of the selected layer.
This is the code I used:
import glob, os
qgis_groups = QgsProject.instance().layerTreeRoot()
path = QgsProject.instance().readPath("./")
operators_path = ''.join((path, '/RSX'))
shp = qgis_groups.findGroup('SHP')
for shp_file in glob.glob(operators_path + "/*.shp"):
layer_name = os.path.splitext(os.path.basename(shp_file))[0]
layer = QgsVectorLayer(shp_file, layer_name, 'ogr')
shp.addLayer(layer)
QgsProject.instance().addMapLayer(layer, False)
iface.setActiveLayer(layer)
Although it looks like we're adding the same layer twice, the registry only recognises each individual layer which we can check by using either the following which returns the list of layers:
registryLayers = QgsProject.instance().mapLayers().keys()
legendLayers = [layer.layerId() for layer in QgsProject.instance().layerTreeRoot().findLayers()]
So there shouldn't be an issue of having layers which are registered in the project file but not visible.
No comments:
Post a Comment