Thursday, 15 September 2016

Changing display name of layer with PyQGIS?


I did a batch processing of several vector layers and now the display name for every file is "dissolved" when accessing the layer.name() function in QGIS. I read in this answer from underdark to Changing layer name of output vector from processing script in QGIS?, that I can set the name to the file name but unfortunaly too late.


I am able to get all the files in my project to be in a list with


layers = iface.mapCanvas().layers()

and all the names with this:


names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]

With the help of this answer to Getting path of project, or layer file in PyQGIS?, I can get the names of the file I am working with:


import os 

real_names = []
for li in layers:
(myDirectory,nameFile) = os.path.split(li.dataProvider().dataSourceUri())
real_names.append(nameFile.split("|")[0]

Reading the API docu for the QgsVectorLayer didnt helped me. What I want is to rename the files to show the filename as display name. How to archive that with the python console?



Answer



You could use something like the following to rename all layers to their respective filename (excluding the extension):


import os


for layer in QgsMapLayerRegistry.instance().mapLayers().values():
basename = os.path.splitext(os.path.basename(layer.source()))[0]
layer.setLayerName(basename)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...