Here's a script to buffer each feature, difference the original from the buffered, and leave the difference in a new layer.
The script operates on the active layer and assumes it is a polygon layer. The results will be unpredictable if it's not.
At the top of the script are two parameters, buf_dist and buf_segments. These have the same meaning as the buffer operation in geoprocessing. Remember that the buf_dist is in the units of the CRS. My test data was in meters, so the buf_dist = 10000 is 10 kilometers.
All the attributes are copied to the new layer, which is called buffer_diff. Attributes that are based on the geometry are NOT recalculated, so areas or perimeters will be wrong.
If you run this from the python console, as each feature is processed you'll get the message "Adding feature". After the last feature is added there may be a noticeable pause before the canvas is repainted.

I've only tried this on a couple of layer files and they were both in the same CRS, so let me know if this fails for your data and I'll see what I can do.


from qgis.utils import iface
from qgis.core import QgsFeatureRequest, QgsProject, QgsSpatialIndex, QgsFillSymbol
from PyQt5.QtCore import Qt

#set the buffer distance in CRS units
buf_dist = 10000
#set # segments for curves
buf_segments = 5


#get the active layer
layer = iface.activeLayer()

#create a memory layer for the new features
#create a url from the layer type and the layer crs
crs = layer.sourceCrs();
url = 'Polygon?crs=' + crs.authid()
print (url)

#create the new memory layer
buf_layer = QgsVectorLayer(url, "buffer_diff", "memory")

#add the attributes of the active layer to the new memory layer`
attrs = layer.dataProvider().fields().toList()
buf_layer.dataProvider().addAttributes(attrs)
buf_layer.updateFields()

feats = []
#loop through the features, creating buffer and difference
for f in layer.getFeatures():
    print("Adding feature")
    geom = f.geometry()
    buf = geom.buffer(float(buf_dist), int(buf_segments))
    dif = buf.difference(geom)
    new_feat = QgsFeature()
    new_feat.setGeometry(dif)
    new_feat.setAttributes(f.attributes())
    feats += [new_feat]
    
buf_layer.dataProvider().addFeatures(feats)
buf_layer.updateExtents()
    
QgsProject.instance().addMapLayer(buf_layer)
_______________________________________________
Qgis-user mailing list
[email protected]
List info: https://lists.osgeo.org/mailman/listinfo/qgis-user
Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-user

Reply via email to