3

Is there a way to modify the input layer, when using QGIS processing algorithms from the Python console?

import processing
layer = iface.activeLayer()
processing.runalg("qgis:multiparttosingleparts", layer, "tmp.shp")

Instead of creating a new shape layer, I want to convert the geometries of the input layer to single-parts.

eclipsed_by_the_moon
  • 1,855
  • 21
  • 44

1 Answers1

1

You can try out this code:

import processing

canvas = iface.mapCanvas()

layers = canvas.layers()

paths = []

for layer in layers:
    if layer.type() == QgsMapLayer.VectorLayer:
        ver = [ feat.geometry().isMultipart() for feat in layer.getFeatures() ]
        if True in ver:
            path = processing.runalg("qgis:multiparttosingleparts", layer, None)
            paths.append(path)

for path in paths:
    new_layer = QgsVectorLayer(path['OUTPUT'],
                               'singlepart',
                               'ogr')

    QgsMapLayerRegistry.instance().addMapLayer(new_layer)

I tested my code duplicating twice one multipart layer in Map Canvas (next image).

enter image description here

Afterward running the code at the Python Console of QGIS I got:

enter image description here

It works!

xunilk
  • 29,891
  • 4
  • 41
  • 80
  • With this code, raster and single part layers will be ignored. – xunilk Mar 13 '17 at 17:38
  • 1
    I don't understand this, it seems that the input layer isn't modified. – eclipsed_by_the_moon Mar 13 '17 at 18:32
  • You can have several multiparts layers loaded at the Map Canvas and the code will process all them and automatically will load its respective singleparts. It will ignore all raster and single part layers. – xunilk Mar 13 '17 at 18:56
  • 1
    Don't understand me wrong, your code is really interesting, but I'm looking for something different. Please check the 'Modify input layer' option of the 'Check geometries" or "Snap Geometries" tool. The multiparttosingleparts example should work the same way. – eclipsed_by_the_moon Mar 13 '17 at 21:40