TransWikia.com

Index of field layer where I have the layer ID PyQGIS 3

Geographic Information Systems Asked on April 28, 2021

I am trying to get the field index of a layer that is input using add vector parameter

self.addParameter(QgsProcessingParameterVectorLayer('Elevationpoints', 'Elevation_points', types=[QgsProcessing.TypeVectorAnyGeometry], defaultValue=None))

This seems to return the layer ID rather than the path. Something like this:

'Elevationpoints_ad0ce945_8f93_4e0e_8fe7_5b053ef287dd'

In the console I get the correct result if I run this with the path-

vlayer = QgsVectorLayer('C:Elevationpoints.shp')
index = vlayer.fields().lookupField('Lidar')
print(index)

By if I try to use the layer ID from the console or the script GUI I get -1 meaning the field was not found.

How can I get the field index from the layer ID?

One Answer

I managed to get it to work using QgsProject.instance().mapLayer . This method does not work if the layer is not already in the map.

#Get the the map layer - this means you need to have the layer in the project or it will not work
pointLayer = QgsProject.instance().mapLayer(parameters['Elevationpoints'])

#get the field index of the point layer
ElevationFieldIndex = pointLayer.fields().lookupField(parameters['ElevationField'])

Answered by Baswein on April 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP