Saturday 29 August 2015

qgis - 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)?



Answer



setLayerName() will rename the layer:


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


Since 2.16 it's QgsMapLayer.setName('thenewname')


Since 3.x it's:


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

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...