PyQGIS – Creating Different Numbers of Random Points Inside Polygons

point-creationpoint-in-polygonpyqgisqgis-processingrandom

I am developing a plugin using PyQGIS and PyQt5. I am calling qgis:randompointsinsidepolygons, where I am trying to give field input at VALUE parameter. It will take a variable number of points for each polygon in the layer. But somehow it is not using field for the same. Attaching the code snippet for the reference.

padding_op.dataProvider().addAttributes([QgsField("vlp1_num", QVariant.Double)])
padding_op.updateFields()

padding_op.startEditing()

for f in padding_op.getFeatures():
    aval_a = (float(f["final_a"])*perc)/100
    vlp1_size = a*b
    f["vlp1_num"] = int(aval_a/vlp1_size)
    padding_op.updateFeature(f)

padding_op.commitChanges() 

num = padding_op.fields().indexFromName('vlp1_num')

random_parameters = {'INPUT':padding_op,
                     'STRATEGY':0,
                     'VALUE':num,
                     'OUTPUT':'memory:'}
random = processing.run('qgis:randompointsinsidepolygons', random_parameters)
random_op = random['OUTPUT']
QgsProject.instance().addMapLayer(random_op)

Here, the number of points to be created in each polygon is stored in vlp1_num field. Algorithm is not considering, it seems.

Best Answer

You pass the index number of the field when using num. Just use QgsProperty.fromExpression('"vlp1_num"') for parameter 'VALUE'.

Related Question