I'm creating a small QGIS3.16 plugin with PyQGIS. I'd want to add a vector (PostGIS) layer to QGIS, and immediately filter it with the QGIS canvas extent.
I found the QgsFeatureRequest(rectangle:QgsRectangle) class. I want to use it with "self.iface.canvas.extent()".
How do I use this class to filter the layer I just added to QGIS?
This is my code :
# Collect the canvas extent
extent = self.iface.mapCanvas().extent()
request = QgsFeatureRequest()
request.setFilterRect(extent)
# Add the vector layer to QGIS
self.uri = QgsDataSourceUri()
self.uri.setConnection("adress", "port", "database", '', '', False,'idauth')
self.uri.setDataSource("schema", tablename, "geomfield", None , pkey)
self.ctrs_cibles=QgsVectorLayer(self.uri.uri(), "layername", "postgres")
root = QgsProject.instance().layerTreeRoot()
if self.ctrs_cibles.featureCount()>0:
QgsProject.instance().addMapLayer(self.ctrs_cibles, False)
root.insertLayer(0, self.ctrs_cibles)
I tried to insert "request" as the 4th parameter of the setDataSource method : self.uri.setDataSource("schema", tablename, "geomfield", request , pkey) But pyQgis waits for a string, not a qgsFeatureRequest.
I've got the same result trying to use setSubsetString. The following command won't work : it needs "request" to be a plain text query.
self.ctrs_cibles.setSubsetString(request)
- I tried to use a getFeatures() method :
for feature in self.ctrs_cibles.getFeatures(request):
do something...
This method needs a qgsFeatureRequest but it just creates an iterator, it doesn't filter the layer. I could use the iterator to create another layer and add the filtered features inside, but I am looking for a more straightforward way to filter a layer with the canvas extent.