PyQGIS – Adding Double Typed Vector Attributes to Layer

pyqgis

I am trying to create a new vector memory layer with attribute data populated as follows and cannot figure out why it works with integer or string typed data but silently does not populate any rows with double typed data.

def create_layer(columns: List[QgsField], data: List[Tuple]):
   layer = QgsVectorLayer('multipoint?crs=epsg:3347', "TEST", "memory")
   provider = layer.dataProvider()
   provider.addAttributes(columns)
   with edit(layer):
      for row in data:
         wkb, attrs = row[0], row[1:]
         geom = QgsGeometry()
         geom.fromWkb(bytearray(wkb))
         feature = QgsFeature()
         feature.setGeometry(geom)
         feature.setAttributes(list(attrs))
         provider.addFeatures([feature])
   return layer

assert create_layer(
   columns=[QgsField('weight', QVariant.Int)],
   data=list(zip(my_geoms, [int(w) for w in my_weights]))
).featureCount() > 0   # PASS

assert create_layer(
   columns=[QgsField('weight', QVariant.String)],
   data=list(zip(my_geoms, [str(w) for w in my_weights]))
).featureCount() > 0   # PASS

assert create_layer(
   columns=[QgsField('weight', QVariant.Double)],  # also tried QgsField('weight', QVariant.Double, 'double' , 8, 6)
   data=list(zip(my_geoms, [round(w, 2) for w in my_weights]))
).featureCount() > 0     # FAILS!

(The length of my_geoms & my_weights are the same & the values of my_weights are Python floats)

Best Answer

I am not sure if it works (because I couldn't produce the same issue), but sometimes you need to cast the value to float. So, try:

data=list(zip(my_geoms, [round(float(w), 2) for w in my_weights]))

or maybe:

data=list(zip(my_geoms, [float(round(w, 2)) for w in my_weights]))