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 = "E:/Geodata/NaturalEarthData/natural_earth_vector.gpkg|layername=ne_110m_populated_places"
vlayer = iface.addVectorLayer(uri, "", "ogr")

By default, the layer name is set to the file name, i.e. natural_earth_vector 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:

{'natural_earth_vector_1a8c3d3c_223d_4bcf_880c_2ce4feebe231': <qgis._core.QgsVectorLayer object at 0x000001DA84D2FEE8>, 
'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!

Advertisement
5 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!!!

  3. Jaime said:

    Hi Anita, when I list layers I did not get buffered layer, I think it happens because buffered variable is missing.
    Thanks for this tutorial, it is what I was looking for.
    Best regards, Jaime

    • Strange, it should be listed. Are you sure you’re using runAndLoadResults() and not just run()?

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 )

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: