I have seen this type of question posed a few times on this site. The solutions that I have gleamed from these questions has helped me. But I have not been able to get my script to produce a result that I would like.
I have a layer in my QGIS 3.10 map called "warn", the actual file path and name is "C:\temp\warn1.shp". I am writing a Toolbox to perform a series of processes on this "warn"-file, with the intention that this file will be called something different in the future.
Some Examples that I have used:
- Getting layer by name in PyQGIS?
- Activating layer by its name in PyQGIS
- How get layer by name in PyQGIS 3.0?
I set up the parameters for the Toolbox as described in the QGIS Template:
self.addParameter(
QgsProcessingParameterFeatureSource(
'INPUT',
self.tr('Area'),
[QgsProcessing.TypeVectorPolygon]
)
)
I call this input in the main script:
Polygon = parameters['INPUT']
When I try and confirm the name of the input using a print statement, a value is returned, but the name contains what appears to be an identifier:
print (Polygon)
Returns:
warn1_940166d7_22bc_47bf_b76c_d75462802047
When I use the Polygon variable in the definition of the layer:
layer = QgsProject.instance().mapLayersByName(Polygon)[0]
I get an "index out of range"
error. Which is expected, as the name does not exist in the map.
How can I return the name of the layer, as it appears in Layer View (Table of Contents)?
In this case I would like "warn" returned.
layer_name = Polygon.split("_")[0]
?