4

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)
5

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 Jan 22 '16 at 11:38
4

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)
  • 1
    That´s more like it. Joesph although finishes it with the rest. Thanks to both of you. – CARTOS Jan 22 '16 at 12:00
  • @MORCKANIAS - Most welcome buddy! I find using multiple answers and mixing them up helps me understand how python syntax works =) – Joseph Jan 22 '16 at 12:03
  • 1
    Yeah @Joseph I missed this part to show off attributes. Glad it help. – SIGIS Jan 22 '16 at 12:30
  • @SIGIS - Haha don't worry, I tend to miss things too, but you got the main question answered anyway :) – Joseph Jan 22 '16 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.