2

I have features selected on the mapcanvas. I want to perform convex hull for those selected features and save those in a memory or store it in a variable preferably and then want to do buffer for the resultant convex hull using python in QGIS.

layer = iface.activeLayer()
features = layer.selectedFeatures()
convex_hull = QgsGeometryAnalyzer().convexHull(layer, path.shp, True, -1, p-None)

The above convexhull function exports the result to a layer but doesnt store. How this can be done?

1 Answer 1

2

This code works well. I used it with a point shapefile (Multi Part) for getting its convexHull Polygon.

layer = iface.activeLayer()
feat = layer.selectedFeatures()[0]

#get geometry
geom = feat.geometry()

convexhull = geom.convexHull()

#Extract CRS from layer
CRS = layer.crs().postgisSrid()

URI = "Polygon?crs=epsg:"+str(CRS)+"&field=id:integer""&index=yes"

#Create polygon layer for convexHull
mem_layer = QgsVectorLayer(URI,
                        "convexhull",
                        "memory")

#add Map Layer to Registry
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

#Prepare mem_layer for editing
mem_layer.startEditing()

#Set feature for convexHull
feat2 = QgsFeature()

#Set geometry for convexHull
feat2.setGeometry(convexhull)

#set attributes values for convexHull
feat2.setAttributes([1])

mem_layer.addFeature(feat2, True)

#stop editing and save changes
mem_layer.commitChanges()

iface.mapCanvas().refresh()

Before running the code in the Python Console (selected features in default yellow color):

enter image description here

After running the code:

enter image description here

Convexhull is a memory layer and it can be saved as shapefile in the directory that you prefer or be used to do a buffer in the same script. Automatically, convexhull becomes the active layer.

2
  • Thank you Xunilk. Great effort! Thanks for your time :-) Works perfectly.
    – User123
    Mar 10, 2015 at 7:14
  • Hi, I tried your code in QGIS3, but it does not work. Do you think much has changed?
    – Lorenzo
    Feb 21, 2020 at 20:22

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.