Expanding upon this post how could you use QGIS to programmatically draw a selection polygon and select features within the polygon? I have been using QgsMapToolEmitPoint(self.canvas)
, to find and select features by point but I am struggling to find a similar polygon solution.
[GIS] Programmatically selecting features by polygon
point-in-polygonpyqgispython-2.7qgis-2select
Best Answer
Check this code for your answer:
https://github.com/dsgoficial/DsgTools/blob/master/ProductionTools/CopyPasteTool/multiLayerSelect.py
On DSGTools, there is a tool called Generic Selector which among other stuff, does exactly what you want. The selection using a polygon is achieved by using the shift modifier in the tool. The tool on the link above is a child of QgsMapTool and we have to reimplement some methods in order to get things done. Explaining the code in a general way, you have to reimplement 3 methods: the canvasPressEvent, canvasReleaseEvent and the canvasMoveEvent.
Let's break the problem into 2 smaller ones:
To build the polygon, you have to click, drag and release. The click event is the canvasPressEvent. In this method, you have to get the coordinate of the beginning of the rectangle, then you have to let the canvasMoveEvent that you have to build the rubberband (polygon that is shown on screen). The code snippet bellow shows you what you can do:
The variable self.isEmittingPoint is used to build the rubberband on the method onCanvasMoveEvent:
The method self.showRect resets and draws the rubberband:
Then, when you release the click, the canvasReleaseEvent is emitted:
On this method, we can achieve the second step, the selection. This tool on DSGTools selects from every layer loaded. To do so, first we have to get the search rectangle, transforming the rubberband into a QgsRectangle. We have implemented a method called rectangle to do so:
After getting the rectangle, we iterate on every layer, get the bbRect and finally select the features using layer.select
I hope I was clear on my answer!