4

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
layer.invertSelection()
inverse = layer.selectedFeatures()

#Erase all the other features with my selected feature
for f in inverse:
    try:
        layer.dataProvider().changeGeometryValues({f.id(): 
        features[0].geometry().makeDifference(f.geometry())})
    except:
        pass
1
  • The link you posted refers to the upcoming QGIS 3.0. Which QGIS version are you using? – mgri Jul 19 '17 at 14:59
6

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():
   feats_list.append(feat)

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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