1

Can someone help me straighten this code out. I want to create three buffers, at 100, 250 and 500m respectively and add these to the contents table. I've tried creating a for loop but not having success. I'm a beginner with Python and the PyQGIS API.

Ideally, I wouldn't have to define the filepath of the outputs, rather save them to the geopackage from which the Layer_to_buffer originates), and I would also like to set the style of each buffered layer.

from qgis import processing
fn = QgsProject.instance().mapLayersByName('Layer_to_buffer')[0]
Output = 'C:/Users/User/Filepath/Buffer'


for x in [100, 250, 500]:
    processing.run("native:buffer",\
      {'INPUT':lyr,\
       'DISTANCE':x,\
       'SEGMENTS':99,\
       'END_CAP_STYLE':0,\
       'JOIN_STYLE':0,\
       'MITER_LIMIT':2,\
       'DISSOLVE':True,\
       'OUTPUT': Output + str(x) +".shp"})
    iface.addVectorLayer(Output, '', 'ogr')
   
0

Try this:

inlayer = iface.activeLayer()

for dis in [500, 250, 100]:
    out_gpkg = inlayer.source().split('|')[0]
    outlayer = 'ogr:dbname=\'{0}\' table="buffer_{1}" (geom)'.format(out_gpkg, dis)
    processing.runAndLoadResults("native:buffer", 
    {'INPUT':inlayer,
    'DISTANCE':dis,
    'SEGMENTS':5,
    'END_CAP_STYLE':0,
    'JOIN_STYLE':0,
    'MITER_LIMIT':2,
    'DISSOLVE':False,
    'OUTPUT':outlayer})

enter image description here

6
  • Unfortunately nothing happens, I get this in the console window: exec(open('C:/Users/alexa/AppData/Local/Temp/tmp_092ixq5.py'.encode('utf-8')).read()) Jan 12 at 19:28
  • 1
    Have you clicked/highlighted your layer to buffer to make it the active layer? Do you have a geopackage input (why are you adding .shp in your code)?
    – BERA
    Jan 12 at 19:28
  • Yes I have. Thank you, it has added the three buffers to my geopackage, but it hasn't added them to the contents table. Are you able to break down the code a little so I can adapt it and edit the styles? Jan 12 at 19:31
  • @BERA interestingly, it didn't work and I didn't expect that. After running the script, .shx and .prj files of inlayer are deleted from the folder and QGIS throws ........ Set SHAPE_RESTORE_SHX config option to YES to restore or create it.) error. Jan 13 at 17:36
  • Ok I only tested with a geopackage input and that worked
    – BERA
    Jan 13 at 17:44

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.