3

I want to create a new vector layer based on an existing one and the extent should be based on the current extent of the canvas. How do I do that?

Edit: I am looking for a quick way to do that (a couple of clicks). I don't want to create any additional layers.

underdark
  • 84,148
  • 21
  • 231
  • 413
ustroetz
  • 7,994
  • 10
  • 72
  • 118

2 Answers2

4

Running the following code in the QGIS Python console clips all features in the currently active layer with a polygon that exactly covers the current viewport, and adds the clipped features to a memory layer:

viewportPolygon = QgsGeometry().fromWkt(iface.mapCanvas().extent().asWktPolygon())
layer = iface.activeLayer()

resultlayer = QgsVectorLayer("Polygon", "result", "memory")
resultlayer.dataProvider().addAttributes(list(layer.dataProvider().fields()))

clippedFeatures = []
for feature in layer.dataProvider().getFeatures():
    clippedGeometry = feature.geometry().intersection(viewportPolygon)

    if not clippedGeometry.isGeosEmpty():
        feature.setGeometry(clippedGeometry)
        clippedFeatures.append(feature)

resultlayer.dataProvider().addFeatures(clippedFeatures)

QgsMapLayerRegistry.instance().addMapLayer(resultlayer)

Jake
  • 6,884
  • 34
  • 43
0

Create a new polygon layer: Layer-> New-> New Shapefile Layer. Draw the new polygon layer over the area of interest, then use the new layer to clip the original vector layer you want cut: Vector-> Geoprocessing Tools-> Clip.

Bernie
  • 653
  • 6
  • 12