4

I am reprojecting a list of files using a for loop

Piece of code:

projection = processing.run('native:reprojectlayer',
    {'INPUT' : inputfile,
    'OUTPUT' : 'memory:',
    'TARGET_CRS' : QgsCoordinateReferenceSystem('EPSG:4326')
    })

Here, 'OUTPUT':'memory:' names all reprojected layers as 'output' which creates confusion. I need each temporary output to be named unique(example: inputfile_name_reprojected).

How can I do that?

Being a beginner, I tried all possible scenarios but nothing worked for me.

1
  • A nice question! I was wondering about the same thing when wrote my answer to this question, where I did it with the result.setName() method. As far as I understood from one PyQGIS guru in his answer here: it is not straightforward. @KadirŞahbaz, please correct me if I am wrong.
    – Taras
    Feb 20, 2022 at 19:00

2 Answers 2

4

Another option is to directly set a name within OUTPUT, like:

projection = processing.run('native:reprojectlayer',
{'INPUT' : inputfile,
'OUTPUT' : 'memory:{}'.format(inputfile.name()+'_reprojected'),
'TARGET_CRS' : QgsCoordinateReferenceSystem('EPSG:4326')
})
2
  • Does this approach also work with .runAndLoadResults()?
    – Taras
    Feb 20, 2022 at 20:02
  • @Taras seems like it doesnt. But you can still use processing.run() and then outlayer = projection['OUTPUT'] + QgsProject.instance().addMapLayer(outlayer)
    – MrXsquared
    Feb 20, 2022 at 20:10
3

A simple approach would be to use layer.setName() within the for loop, like:

for inlayer in iface.layerTreeView().selectedLayers():
    projection = processing.run('native:reprojectlayer',
    {'INPUT' : inlayer,
    'OUTPUT' : 'memory:',
    'TARGET_CRS' : QgsCoordinateReferenceSystem('EPSG:4326')
    })
    outlayer = projection['OUTPUT'] # get the output
    outlayer.setName(inlayer.name()+'_reprojected') # rename the output
    QgsProject.instance().addMapLayer(outlayer) # add the output to canvas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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