Saturday, 19 May 2018

python - Using processing algorithm in QGIS plugin


I'm building a plugin in QGIS, one of its part is processing algorithm: intersection. I want to save the result as memory layer, and then work on it. Following code was working fine, nothing changed (I changed nothing), and: boom! it stopped working. The problem is in the 2nd line:


processing.runandload("qgis:intersection",selectedLayer,selectedLayer_2, "memory:temp_layer")

layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:temp_layer")[0]

The memory layer is created (I can see it in QGIS) but I can't define 'layer'. I'm getting an error:



IndexError: list index out of range.



Why? :(



Answer



I suspect this is probably dependent on the Processing plugin version for each of those computers. Your following line checks the list of loaded layers and will only define layer if a layer has the name memory:temp_layer.


layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:temp_layer")[0]


In the older versions of the Processing plugin, you can define the name of the memory layer "memory:any_name". The line above will work.


In the latest versions, the default name of the tool is used instead (e.g. "Intersection"). The line above will not work.




I would suggest checking the Processing plugin for each of your computers and updating it to the latest version (currently at 2.12.2) from the toolbar:


Plugins > Manage and Install Plugins...


And use the following line instead:


layer = QgsMapLayerRegistry.instance().mapLayersByName("Intersection")[0]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...