Geographic Information Systems Asked on March 5, 2021
I have some layers loaded in QGIS, in various groups. I want, with PyQGIS, do some stuff on layers from one of theses groups, like adding geometry type to the layer name.
This way, I can do it on all layers :
layers = QgsProject.instance().mapLayers().values()
for layer in layers:
layer.setName(layer.name()+"_"+QgsWkbTypes.displayString(layer.wkbType()))
This way, I can access layer names from one specific group :
root = QgsProject.instance().layerTreeRoot()
my_group = root.findGroup('My group')
for layer in my_group.children():
print(layer.name())
if isinstance(layer, QgsLayerTreeLayer):
layer.setName(layer.name()+"_"+QgsWkbTypes.displayString(layer.wkbType()))
The "print" of layer name works, but I can’t change name, either get the geometry type. I get this error :
AttributeError: 'QgsLayerTreeLayer' object has no attribute 'wkbType'
Does someone know what is the correct way to do that?
You should add layer()
method to layer
object. layer
is an instance of QgsLayerTreeLayer
. It doesn't have wkbType
attribute, but QgsVectorLayer
has.
Change layer.wkbType()
to layer.layer().wkbType()
. layer.layer()
returns the map layer associated with layer
.
root = QgsProject.instance().layerTreeRoot()
my_group = root.findGroup('My group')
for layer in my_group.children():
if isinstance(layer, QgsLayerTreeLayer):
layer.setName(layer.name() + "_" + QgsWkbTypes.displayString(layer.layer().wkbType()))
Correct answer by Kadir Şahbaz on March 5, 2021
If each layer of your QGIS project has a unique name, you can use the following code.
The loop retrieves the name of the layers of your group then you will identify the layer with the mapLayersByName
method and you will be able to manipulate it easily.
root = QgsProject.instance().layerTreeRoot()
my_group = root.findGroup('My group')
layer_list = [layer.name() for layer in my_group.children()]
for layer in layer_list:
update_layer = QgsProject.instance().mapLayersByName(layer)
for lay in update_layer:
lay.setName(lay.name()+"_" +QgsWkbTypes.displayString(lay.wkbType()))
Answered by Vincent Bré on March 5, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP