I have a problem creating a copy of a layer in pyqgis with layer.materialize()
. Namely, it leaves out one (or none) features from the original layer, depending on the layer.
E.g. when I run this code with a particular layer with 129 features, it consistently copies 128 of them, and always leaves out a single one:
new_layer = layer.materialize(QgsFeatureRequest())
ftr = QgsFeature()
layer.getFeatures(QgsFeatureRequest().setFilterExpression("jd = '4583-3809-1068-6280'")).nextFeature(ftr)
print("Original:", ftr.isValid())
new_layer.getFeatures(QgsFeatureRequest().setFilterExpression("jd = '4583-3809-1068-6280'")).nextFeature(ftr)
print(" New:", ftr.isValid())
produces
Original got the SEK: True
New got the SEK: False
When I run it on another layer (of the same type) with 357 features I get all of them in the new layer.
A feature is left out in about half of cases (from my dataset).
I cannot find no particularity that would distinct the one feature left out. So far I have only noticed this on layers with QgsWkbTypes.Point
features.
No errors or warnings or anything is reported in the process...
Does anyone have an idea what could be wrong?
Edit:
The workaround (at least for me) seems to be cloning the layer, writing it to a new location (which I have to anyways), and then reloading it from there:
new_layer = layer.clone()
options = QgsVectorFileWriter.SaveVectorOptions()
options.fileEncoding = 'UTF-8'
options.driverName = "ESRI Shapefile"
(err,e1,e2,e3) = QgsVectorFileWriter.writeAsVectorFormatV3(new_layer, file_name, QgsCoordinateTransformContext(), options)
if err != QgsVectorFileWriter.NoError:
raise Exception(f"Creating layer {name} in '{file_name}' failed: {e1} / {e2} / {e3}")
new_layer = QgsVectorLayer(file_name, name, 'ogr')