[GIS] How to transform a selected multipart feature into singlepart features while editing in QGIS

pyqgispythonqgisqgis-plugins

There are several questions and respective answers for how to make a multipart features Layer into a singlepart features one using QGIS:

But all the solutions I saw, create entirely new layer and would transform ALL the multipart geometries into single ones.

So the questions is, how could one, during an edit session, selectively transform a multipart feature into a singlepart feature, without the need to create new layers?

It would be the opposite to the "merge selected features" tool, and similar to explode in ArcGIS.

Is there any plugin doing this? How could this be done using the python console?

Best Answer

Inspired by this question & answer as an example of how "easily" can one make its own solutions when using Open Source, I have tried to create my own code to selectively "explode" multipart features during an editing session.

I have explored the QGIS 1.8 API for the first time, and came out with this piece of code that seams to do the job:

layer = qgis.utils.iface.mapCanvas().currentLayer()
remove_list = []

for feature in layer.selectedFeatures():
    geom = feature.geometry()
    # check if feature geometry is multipart
    if geom.isMultipart():
        remove_list.append(feature.id())
        new_features = []
        temp_feature = QgsFeature(feature)
        # create a new feature using the geometry of each part
        for part in geom.asGeometryCollection ():
            temp_feature.setGeometry(part)
            new_features.append(QgsFeature(temp_feature))
        # add new features to layer
        layer.addFeatures(new_features, False)

# remove the original (multipart) features from layer
if len(remove_list) > 0:
    for id in remove_list:
        layer.deleteFeature (id)    

I'm not an experienced programmer, so the code might not be the most efficient one.

Next steep will be to make a plugin out of it... Or at least, try to!

UPDATE:
I was able to create the plugin. It's called Multipart Split, and can be found in the QGIS official repository.

Related Question