8

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?

7

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.