In the PyQGIS documentation for QgsSpatialIndex.nearestNeighbor
(https://qgis.org/pyqgis/master/core/QgsSpatialIndex.html#qgis.core.QgsSpatialIndex.nearestNeighbor)
we see the following (!) Warning:
If this
QgsSpatialIndex
object was not constructed with the FlagStoreFeatureGeometries flag, then the nearest neighbor test is performed based on the feature bounding boxes ONLY, so for non-point geometry features this method is not guaranteed to return the actual closest neighbors.
Neither in the cookbook (https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#using-spatial-index) nor somewhere else on the web I could find an example on the question
How to construct a QgsSpatialIndex with the FlagStoreFeatureGeometries flag in PyQGIS?
(related: Why does QgsSpatialIndex.nearestNeighbor(point, 1) sometimes return 2 lines?)