I would like to do a "difference" between 2 features in PyQGIS.

I don't understand how to use the method makeDifference() as shown on the documentation here.

It says the parameter to pass the function is:

QgsGeometry makeDifference (const QgsGeometry &other)

I have tried the following code but don't see any change in the feature.

layers = iface.legendInterface().layers()
layer = layers[0]

# I select the feature that will erase all the others
features = layer.selectedFeatures()

#Get the other features
inverse = layer.selectedFeatures()

#Erase all the other features with my selected feature
for f in inverse:
  • The link you posted refers to the upcoming QGIS 3.0. Which QGIS version are you using?
    – mgri
    Jul 19, 2017 at 14:59

1 Answer 1


If you need to perform a simple difference operation between to features, the difference() method should be enough.

Assuming to start from two features stored in a list:

layer = iface.activeLayer()
feats_list = []
for feat in layer.getFeatures():

print feats_list
# 'feats_list' is something like:
# [<qgis._core.QgsFeature object at 0x17658A30>, <qgis._core.QgsFeature object at 0x17658A80>]

you preliminarily need to get the geometry of each feature:

geoms_list = [item.geometry() for item in feats_list]

print geoms_list
# 'geoms_list' is something like:
# [<qgis._core.QgsGeometry object at 0x17658B70>, <qgis._core.QgsGeometry object at 0x176589E0>]

and the evaluating the difference between them:

geom1 = geoms_list[0]
geom2 = geoms_list[1]

diff = geom1.difference(geom2)

The diff variable will be still a geometry object. You can then use it for creating a new feature and add it to a layer.

  • @Blue I'm glad it was helpful!
    – mgri
    Jul 19, 2017 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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