Advertisements

In previous examples, we already covered adding layers from files as well as creating new layers from scratch. In this example, we explore how to rename and delete layers.

First, let’s load a vector layer:

import processing
uri = "D:/Documents/Geodata/NaturalEarthData/Natural_Earth_quick_start/110m_cultural/ne_110m_populated_places.shp"
vlayer = iface.addVectorLayer(uri, "", "ogr")

By default, the layer name is set to the file name, i.e. ne_110m_populated_places. Renaming this layer is straightforward:

vlayer.setName('Places')

To add a different second layer to our project, let’s buffer the points:

processing.runAndLoadResults("native:buffer", {'INPUT':uri,'DISTANCE':10,'SEGMENTS':5,'END_CAP_STYLE':0,'JOIN_STYLE':0,'MITER_LIMIT':2,'DISSOLVE':False,'OUTPUT':'memory:'})

Our project now contains two layers. To get a list of all layers in our project, we can call the project’s mapLayers() function:

project = QgsProject.instance()
print(project.mapLayers())

The mapLayers() function returns a dictionary of layer ids and corresponding layer objects:

{'ne_110m_populated_places_7ec022f9_40e5_415f_b582_d24d1d0ecd44': <qgis._core.QgsVectorLayer object at 0x0000013B944B3288>, 
'output_551f6269_c5ea_4730_aa72_42a3fa86cb77': <qgis._core.QgsVectorLayer object at 0x0000013B944B3828>}

To print the layer names instead, we can iterate through the dictionary items:

for id, layer in project.mapLayers().items():
    print(layer.name())


Places
Buffered

To rename the layer named Buffered, we first need to find the layer object. Layers can be identified by id or by name. Since we don’t know the buffer layer’s id, we need to use the name. There is one challenge though: names are not necessarily unique! That means that multiple layers can have the same name. Therefore the function project.mapLayersByName() returns a list of layers. If we know that there’s only one layer with the given name, we can access the first entry in this list by appending [0]:

to_be_renamed = project.mapLayersByName('Buffered')[0]
to_be_renamed.setName('Renamed!')

Finally, to remove a layer from our project, we can use the project.removeMapLayer() function. This function requires the layer id:

to_be_deleted = project.mapLayersByName('Places')[0]
project.removeMapLayer(to_be_deleted.id())
# equivalent to: project.removeMapLayer(vlayer.id())

These are the basics of managing layers in a QgsProject.

Next


PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!

Advertisements
3 comments
  1. Amazing introduction to PyQGIS; it helped me a lot. Thank you!

  2. Loving this tutorial series! I am new to the PyQGIS environment, and Python in general, these tutorials have been really helpful. I was wondering if for an upcoming tutorial you could go through performing some mathematical operations on a field in a layer (sum, divide by another field, etc). Once again, great tutorials. I am also planning on purchasing your cartography book for QGIS! Thanks!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: