I have figured out how to save only the features of a vector layer that intersect a rectangle (I'm doing something similar to the example below):
TransformContext = QgsProject.instance().transformContext()
SaveOptions = QgsVectorFileWriter.SaveVectorOptions()
SaveOptions.driverName = "GPKG"
listOfLayers : list[QgsMapLayer] = layerIdsToLayers.values()
for layer in listOfLayers:
currentExtentsToSave = QgsRectangle(0, 0, 1, 1)
SaveOptions.filterExtent = currentExtentsToSave
SaveOptions.onlySelectedFeatures = False
SaveOptions.actionOnExistingFile = QgsVectorFileWriter.ActionOnExistingFile.CreateOrOverwriteLayer
fileName = "Example.gpkg"
QgsVectorFileWriter.writeAsVectorFormatV3(layer, fileName, TransformContext, SaveOptions)
With some testing, I confirmed that the calculation to determine overlap checks if any parts of the geometry of each feature overlap with the extents provided in the SaveOptions.
How can I modify the SaveOptions so that the calculation performed to determine an overlap only uses the center of each feature's geometry?
QgsRectanglein thefilterExtent. However, one could try theQgsFeatureRequestwith.setFilterExpression()together with thematerializeto create a temp layer. Additionally, it is better to switch towriteAsVectorFormatV3as v1 and v2 are deprecated since QGIS 3.40 and QGIS 3.20, correspondingly.