After running Processing algorithm ending up with a layer by runalg
or runandload
in QGIS2, run
or runAndLoadResults
in QGIS 3, these methods return a result which is mostly a dictionary like {'OUTPUT': 'file_path'}
etc. So, after result = processing.run*(...),
I can get the output by result['OUTPUT'].
But its value is mostly just a string.
If it would be a method like processing.run*(...)
that returns an instance of output instead of file path, we would get the layer reference by writing just layer = processing.run*(...)
.
Is there any processing.run*()
method that returns layer instance/reference directly, e.g. QgsVectorLayer
?
Best Answer
Please note that all solutions explained here are related to vector layer used as the input and QGIS native algorithms. The answer doesn't explain the results of other providers' tools. (GRASS, GDAL, SAGA, ...). They may be different from native ones.
QGIS 3:
OPTION 1:
run()
method with memory output:Result is a dictionary.
result['OUTPUT']
gives an instance of a layer (QgsVectorLayer
). No layer is added. Option 1 is one and only solution that returns a reference forQgsVectorLayer
in QGIS 3.It can be used in the following way:
result_layer
is nowqgis._core.QgsVectorLayer
. Since it's a memory layer, it should be added to the project usingaddMapLayer()
method.Other Processing Options
OPTION 2:
run()
method with file output:Result is a dictionary, value is a string. No layer is added.
OPTION 3:
runAndLoadResults()
method with file outputResult is a dictionary, value is a string. A layer is added.
OPTION 4:
runAndLoadResults()
method with memory outputResult is a dictionary, value is a string. A layer is added.
QGIS 2:
OPTION 1:
runandload()
method with file outputResult is an instance of related algorithm class. A layer is added.
OPTION 2:
runandload()
method with memory outputResult is an instance of related algorithm class. A layer is added.
OPTION 3:
runalg()
method with file outputResult is a dictionary, value is a string. No layer is added.
OPTION 4:
runalg()
method with memory outputResult is a dictionary, value is a string. No layer is added.
Neither
runalg
norrunandload
returns a layer reference/instance for output in QGIS 2.