PyQGIS Layer Selection – Techniques for Selecting Layers in PyQGIS

pyqgisqgis-3

*Python 3.7 and QGIS 3.6

I have a program that loads multiple layers, and now I need to select different layers to edit. Before I was managing fine with iface.activeLayer(), but now that I have multiple layers this is no longer an option.

My current code – additional layers are loaded later:

layer = iface.addVectorLayer(in_file, name, 'ogr')

iface.mapCanvas().refreshAllLayers()
layer = iface.mapCanvas().layer(0)

layer.startEditing()

This results in the following error:

AttributeError: 'NoneType' object has no attribute 'startEditing'

Interestingly, if I run the code when there is already a layer loaded, it works. This isn't an actual fix though, as it's not realistic for me to have a layer pre-loaded each time I run the code.

Best Answer

You should be able to do something like:

in_file =  r'C:\Full\Path\To\Vector\File.gpkg'
name = 'Layer Name'
layer = QgsVectorLayer(in_file, name, 'ogr')
QgsProject().instance().addMapLayer(layer)
layer.startEditing()

I tested this in QGIS 3.4 on a new project and it worked fine with no other layers loaded (see image below).

enter image description here

It should also work fine when loading subsequent layers. However, if you want to be more explicit in referencing a layer, you could use something like the following (assuming that the name variable holds the reference to the name of the layer you want to put into edit mode):

in_file =  r'C:\Full\Path\To\Vector\File.gpkg'
name = 'Layer Name'
layer = QgsVectorLayer(in_file, name, 'ogr')
QgsProject().instance().addMapLayer(layer)
layer_to_edit = QgsProject().instance().mapLayersByName(name)[0]
layer_to_edit.startEditing()