I want to search on number values (>, = etc.) within a column and open table for the selected ones. It's an easy task within field calculator, but I want to see how it's build up with the python syntax and then run it. It would help me understand. Or should I run it with the consols editor?
While this is an expression by the attribute (population) i won't need the feature-class, right?
What I want is something like this:
def "population" < 2000
def showAttributeTable() (but only for the selected ones)
2 Answers 2
There's various way how to do it and depends on what you want.
Solution 1 : with selection assuming you've already select your features :
# My layer test
Layer=QgsVectorLayer("path/to/shapefile.shp","Display name", "ogr")
# list of selected features
selected_features = [ feature for feature in layer.selectedFeatures()]
Solution 2 : with the querie builder :
# My layer test
Layer=QgsVectorLayer("path/to/shapefile.shp","Display name", "ogr")
# set a querie like querie builder in properties
Layer.setSubsetString(u'"population" < 2000')
list_of_features = [feature for feature in layer.getFeatures()]
# reset the querie
layer.setSubsetString("")
I would use the first one for spatial selection and the other one for queries on attributs field
-
Thanks, but that doesn´t generate any output. Instead of first line I suggest I could use: layer = iface.activeLayer()CARTOS– CARTOS2016年01月22日 11:38:41 +00:00Commented Jan 22, 2016 at 11:38
Great answer by @SIGIS! You could also use the following to set your current layer, set the expression and load the Attributes Table with the selected features:
layer = qgis.utils.iface.activeLayer()
exp = QgsExpression( "\"population\"< 2000" )
ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(exp))]
layer.setSelectedFeatures(ids)
qgis.utils.iface.showAttributeTable(layer)
-
1That´s more like it. Joesph although finishes it with the rest. Thanks to both of you.CARTOS– CARTOS2016年01月22日 12:00:48 +00:00Commented Jan 22, 2016 at 12:00
-
@MORCKANIAS - Most welcome buddy! I find using multiple answers and mixing them up helps me understand how python syntax works =)Joseph– Joseph2016年01月22日 12:03:28 +00:00Commented Jan 22, 2016 at 12:03
-
1Yeah @Joseph I missed this part to show off attributes. Glad it help.SIGIS– SIGIS2016年01月22日 12:30:50 +00:00Commented Jan 22, 2016 at 12:30
-
@SIGIS - Haha don't worry, I tend to miss things too, but you got the main question answered anyway :)Joseph– Joseph2016年01月22日 12:33:00 +00:00Commented Jan 22, 2016 at 12:33