@GermánCarrillo already provided a pretty useful link to a great answer. Here is something more specific about your script, where there are a few issues:
- Since you are looking for intersecting features, there is no need to sort the layer by ids (or is there something you did not mention?)
- You are iterating over the whole layer for each feature and checking the index (incorrectly) afterwards, so there is pretty no performance gain in the index usage. Instead, for each feature, iterate over the index only.
- You can store the features geometries directly inside the index by using
flags=QgsSpatialIndex.FlagStoreFeatureGeometries
so you can avoid an inperformant feature request and instead get the geometry from the index much faster
- Dont forget to exclude self-intersections; otherwise your entire layer will be deleted
- If the index matches this does not mean that the features actually intersect, that only means the bounding box intersects, so you need to do an actual intersects-test on the matches.
- There is no need to do a selection if you only want to delete the features
Try this:
layer = iface.activeLayer()
index = QgsSpatialIndex(layer.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
featids = []
for feat in layer.getFeatures():
for fid in index.intersects(feat.geometry().boundingBox()): # iterate over the index-matches. The index returns the IDs of the features where the boundingbox intersects
if fid == feat.id(): # ignore self-intersections
continue
fgeom = index.geometry(fid) # get the feature geometry by the id from the index
if fgeom.intersects(feat.geometry()): # now check if not only the bounding box intersects, but if the actual features geometries intersect
featids.append(feat.id()) # if so append the id to a list for selection afterwards
layer.startEditing()
layer.deleteFeatures(featids)
layer.commitChanges()