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.

Lilium
  • 1,057
  • 1
  • 6
  • 17
  • 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 '22 at 19:00

2 Answers2

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')
})
MrXsquared
  • 34,292
  • 21
  • 67
  • 117
  • Does this approach also work with .runAndLoadResults()? – Taras Feb 20 '22 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 '22 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
MrXsquared
  • 34,292
  • 21
  • 67
  • 117