Rename layers with PyQGIS script

Just discovered QGIS and really impressed! I've not formal GIS training so rely on Google to figure stuff out.

I'm using the SHP files made available by the Canadian Government as part of their CANVEC+ set. The SHP files are made available by NTS map sheet.

The naming shows what of data is in the layer. I've a batch files that copies the layers I'm interested in out of a mapsheet dir.

I was trying to rename the Layer with a PyQGIS script. Examples on the internet got me to the point of being able to list the layers. If statements to match what I need. But have been unable to find if I can assign a new name value that way?

Is there a better way to do this, because I'm guessing this a pretty common problem?

Can I use the same script logic to assign a transparency (or maybe even a style)?

setLayerName()will rename the layer:

for layer in QgsMapLayerRegistry.instance().mapLayers().values(): layer.setLayerName('NewName')

Since 2.16 it'sQgsMapLayer.setName('thenewname')

Since 3.x it's:

for layer in iface.layerTreeView().selectedLayers(): layer.setName('NewName')

This script (for QGIS 3) iterates over all layers in the project and replaces chosen text in their name. Simply paste this inside the QGIS Python Console. This works for QGIS 3

layerList = QgsProject.instance().layerTreeRoot().findLayers() for layer in layerList: basename = layer.setName(basename.replace("db_prefix_to_be_followed_by_a_space ",""))

or, if you wish to do this only over selected layers in the layer panel:

for layer in iface.layerTreeView().selectedLayers(): basename = layer.setName(basename.replace("db_prefix_to_be_followed_by_a_space ",""))

(do not forget to put the offending space inside the first quotation marks) (the empty text inside the second quotation marks will effectively erase the text found in the first quotation marks)

This will serve when adding a database (such as gpkg or fgdb) to a project to remove the database name prefixed on the layer name. This will also make it easier to reference those layers in the DB_manager because the spaces in the names are not compatible with the autocomplete. (as of 3.8)

The other answer as well as this other question (Stuck on how to list loaded layers in QGIS 3 via Python) got me to come up with this complete solution.

Also, as seen in the other answer, use this for QGIS 2


Watch the video: QGIS Python PyQGIS - Get raster band data with GDAL (October 2021).