2

I'm trying to set up a Buffer from Geoprocessing Tools and i would like to put a Field from the layer as Distance Souce.

Here is my code :

import processing
layer =  QgsVectorLayer(path_to_routes, 'Routes', "ogr")
QgsProject.instance().addMapLayer(layer)
processing.run('native:buffer', {"INPUT": layer, "DISTANCE":50, "OUTPUT": memory:buffer})

I don't find a solution to put a field on "DISTANCE" parameter.

Here is a picture of what i want to set up.

enter image description here

2

If you want to reference an existing field in a parameter, you could use:

QgsProperty.fromExpression('"fieldName"')

So your code would look like:

import processing
layer = QgsVectorLayer(path_to_routes, 'Routes', "ogr")
QgsProject.instance().addMapLayer(layer)
processing.run('native:buffer', {"INPUT": layer, "DISTANCE":QgsProperty.fromExpression('"fieldName"'), "OUTPUT": 'memory:buffer'})
  • 2
    Cool, I went with layer.dataProvider().fieldNameIndex('DISTANCE'), but it did not work. QgsProperty.fromExpression instead works on a feature per feature basis. – RafDouglas Jun 11 at 11:16
  • 1
    Again, thank you @Joseph, i used .fromExpression but not with QgsProperty classe. Thanks ! – Valentin L. Jun 11 at 13:02
  • 1
    @RafDouglas - Good to know, thanks for your comment :) – Joseph Jun 12 at 9:23
  • @ValentinL. - Most welcome! Glad it helped :) – Joseph Jun 12 at 9:23
1

You are almost there :)

GUI option

Use the "Assistant" option:

enter image description here

then:

  • Select the field you want to use as a buffer distance
  • Elick on the reload icon to see the data range
  • Enter the same min-max values in the fields below Output from and to

enter image description here

PyQGIS

Expanding on Joseph's answer:

from qgis.core import (
    QgsVectorLayer,
    QgsProject,
    QgsProperty
)
import processing

input = "/tmp/QGIS3-6iz04U/temp.shp"
layer = QgsVectorLayer(input,"polygon","ogr")

processing.run("native:buffer", {
    'INPUT': layer,
    'DISTANCE': QgsProperty.fromExpression('"DISTANCE"'),
    'SEGMENTS': 10,
    'DISSOLVE': False,
    'END_CAP_STYLE': 0,
    'JOIN_STYLE': 0,
    'MITER_LIMIT': 10,
    'OUTPUT': '/tmp/QGIS3-6iz04U/buffers.shp'})
blayer = QgsVectorLayer('/tmp/QGIS3-6iz04U/buffers.shp',"buf","ogr")    
QgsProject.instance().addMapLayer(blayer)
  • I don't understand how i'm supposed to connect this to my code ? I fail to my explanations. What i want is put on "DISTANCE" paramater in the processing.run not 50 like in my code but a field like 'ID' which create the buffer with this feature. – Valentin L. Jun 11 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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