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.

1
  • There are several ways but you can use, e.g., QgsMapCanvas objects. Please, see my answer.
    – xunilk
    Mar 13, 2017 at 16:43

1 Answer 1

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!

4
  • With this code, raster and single part layers will be ignored.
    – xunilk
    Mar 13, 2017 at 17:38
  • 1
    I don't understand this, it seems that the input layer isn't modified. Mar 13, 2017 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, 2017 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. Mar 13, 2017 at 21:40

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