PyQGIS: Clip Vector Layers
It is very simple to clip vector layers with PyQGIS. This tutorial will demonstrate how to use Python in QGIS to clip a line layer with a polygon layer.
First, import the processing module and set the paths to the line, polygon and output layers.
import processing #set input and output file names polyPath = "C:/temp/buffer_clip.shp" linePath = "C:/temp/streams_clip.shp" clipPath = "C:/temp/clipped.shp"
The next step is to run the clip tool. This is accomplished with a call to processing.run()
. We pass the name of the processing tool, in the case the QGIS native clip tool, and a dictionary containing the input parameters for the tool. For the clip tool the only parameters are the file paths we defined in the first step. This block of code will perform the analysis and save the clipped features to a new shapefile.
#run the clip tool processing.run("native:clip", {'INPUT':linePath,\ 'OVERLAY':polyPath,\ 'OUTPUT':clipPath}) #add output to the qgis interface iface.addVectorLayer(clipPath, '', 'ogr')
Now add the clipped layer to the QGIS interface.
#add output to the qgis interface iface.addVectorLayer(clipPath, '', 'ogr')
The full code block and a video demonstrating the process are below.
import processing #set input and output file names polyPath = "C:/temp/buffer_clip.shp" linePath = "C:/temp/streams_clip.shp" clipPath = "C:/temp/clipped.shp" #run the clip tool processing.run("native:clip", {'INPUT':linePath,\ 'OVERLAY':polyPath,\ 'OUTPUT':clipPath}) #add output to the qgis interface iface.addVectorLayer(clipPath, '', 'ogr')