4

In QGIS 3 I am trying to get a layer in the Python Console. And I have to put to arguments in the function QgsProcessingUtils.mapLayerFromString(). The first argument is self-explanatory, the string. But I don't understand what the second argument is (the QgsProject).

Could someone clarify me what that second argument is?

1
  • The second argument is the context. Try QgsProject.instance().
    – christoph
    Commented Sep 11, 2020 at 16:39

2 Answers 2

2

The second argument in QgsProcessingUtils.mapLayerFromString() refers to context i.e. QgsProcessingContext e.g. information that wraps your QgsProject.

Interprets a string as a map layer within the supplied context.

The method will attempt to load a layer matching the passed string. E.g. if the string matches a layer ID or name within the context's project or temporary layer store then this layer will be returned. If the string is a file path and allowLoadingNewLayers is true, then the layer at this file path will be loaded and added to the context's temporary layer store. Ownership of the layer remains with the context or the context's current project.

The typeHint can be used to dictate the type of map layer expected.

More details can be found in this thread: What does context mean in PyQGIS?

1

There are several ways to access the layers. As @christoph tells you, it is easier and more direct to use the methods of QgsProject.

We start by instantiating pry=QgsProject.instance()

1.- To access a layer by its name you can use

pry.mapLayersByName()

It returns a list, because you can have several layers with the same name. If only one layer matches, you can access it by its index:

pry.mapLayersByName("transport")[0]

2.- From QGIS3.10 you also have the mapLayersByShortName() method

3.- If you want a list with all the layers:

pry.mapLayers()

Returns a dictionary, the layer id is the key

On the other hand, you can combine with the methods of iface (QgisInterface) and QgsMapCanvas

1.- Get the active layer**:

  • iface.activeLayer() returns the active layer
  • iface.mapCanvas().currentLayer() generates the same result

2.- A list of the layers visible on the canvas

iface.mapCanvas().layers()
1
  • 3
    All is true but not answering the question. Commented Sep 12, 2020 at 5:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.