1

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')
3
  • Can you share this layer with us?
    – Taras
    Commented Jun 6, 2023 at 10:03
  • What you apply this new_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.allFeatureIds()))
    – Taras
    Commented Jun 6, 2023 at 10:08
  • Setting filter didn't help. Commented Jun 7, 2023 at 4:35

1 Answer 1

3

I found the cause: one of the string attributes of the left=out feature was a single character too long as per definition. As no errors are reported when creating the feature in the origin layer or when cloning/materializing the layer it was really hard to find.

materialize() seems to only copy the features that conform to the fields definitions.

1
  • 1
    Please file a feature request to emit a warning or something when that happens, sounds like a very hard to find issue. Commented Jun 7, 2023 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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