Have you ever needed to explode multi geometry layer into a single geometry layer, using in each new geometry the attributes of the original multi one? If you were working with FME, for instance, you basically would just use the transformer Deaggregator. Let’s learn how to solve this problem with python and QGIS!
The following code snippet teaches you how to work with QgsVectorLayers, it’s attributes and how to manipulate geometries.
from qgis.core import QgsVectorLayer, QgsFeature, QgsMapLayerRegistry #fill in your input layer name. In this example, our inputLyrName is input_layer inputLyrName = 'input_layer' inputLyr = QgsMapLayerRegistry.instance().mapLayersByName(inputLyrName) #fill in your output layer name. In this example, our outputLyrName is output_layer outputName = 'output_layer' outputLyr = QgsMapLayerRegistry.instance().mapLayersByName(outputLyrName) #tests type of output: if it is a multi parted geometry or #a single parted geometry if outputLyr.wkbType() in [QGis.WKBPoint, QGis.WKBLineString, QGis.WKBPolygon]: isMulti = False else: isMulti = True outputLyr.startEditing() addList =  for feat in inputLyr.getFeatures(): #gets all parts of geometry as an individual single geometry parts = feat.geometry().asGeometryCollection() #checks if it isMulti, if it is, convert each #part in geometryCollection to multi if isMulti: for part in parts: part.convertToMultiType() #for each part, get original set of attribute and create a new feat #with this set for i in range(0,len(parts)): #new feature constructor. newFeat has all atributes of feat newFeat = QgsFeature(feat) #set geometry with part newFeat.setGeometry(parts[i]) #get field id and get defaultValue from provider idx = newFeat.fieldNameIndex('id') newFeat.setAttribute(idx,provider.defaultValue(idx)) addList.append(newFeat) outputLyr.addFeatures(addList,True) outputLyr.commitChanges()
Hope you guys like it!