Friday, 31 January 2020

Hide unselected features with pyqgis


In the context of QGIS/PyQGIS, I would like to hide the unselected features after performing, for example, a simple selection.


feature = layer.getFeatures().next()
layer.setSelectedFeatures([feature.id()])

After running this commands a feature becomes highlighted. Besides, I'd like to hide the unselected features. How can I do that?


I believe this is possible because the Query Builder performs a filter that hides the undesired features.



Answer



I just made it. In fact, I should use the setSubsetString method. Then I built a a query string inside a loop in order to look like this "gid IN ('8816','8836','8839','8864')". Then, when you run the setSubsetString method it hides the features that are not specified in the query string.



#Do any spacial query which returns some features
features = lyrPnts.getFeatures(QgsFeatureRequest().setFilterRect(geomPoly.boundingBox()))

#build the query string
strsel="gid IN ("
for feat in features:
if feat.geometry().intersects(geomPoly):
strsel=strsel+ "'" + str(feat.id()) + "',"

#Closes the string with a parenthesis

strsel=strsel[:-1] + ")"
#Hides the undesired features
lyrPnts.setSubsetString(strsel)

Nice job


Alex


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...