Selecting features using expressions

Using expressions, you can iterate through features and evaluate the expression returning true(1) or false(0). Before we get into expressions, let's select and highlight a feature. Selecting a feature is accomplished by calling setSelectedFeatures() and passing a list of IDs. The following code will select a single feature:

from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
iface.mapCanvas().setSelectionColor( QColor("red") )
scf.setSelectedFeatures([100])

The previous code, imports QtGUI, and Qt.Widgets. These are needed to set the color using QColor. The next line gets the map canvas and sets the section color to red. Lastly, the code selects the feature with an id of 100. It will now display red on the map.

The previous example assumes you want to select a single feature and that you know the id. That is rarely the case. More often than not you will want to select by some condition—or using an expression. Using QgsExpression() you can pass an expression string and evaluate it against features. The following code shows you how:

closed=[] 
exp=QgsExpression("Type='Traffic Signs' and Status='Acknowledged'")
exp.prepare(scf.pendingFields())
for f in scf.getFeatures():
if exp.evaluate(f)==1:
closed.append(f.id())
scf.setSelectedFeatures(closed)

First, the previous code creates a list, closed, to store the IDs where the expression evaluates to true. Next the expression is declared. The expression checks for two conditions on the Type and Status. The expression is prepared and passed the fields in the layer. The next line iterates through the features. If the expression is true (1), the id is put in the list. Lastly, the selected features are set to the IDs in the closed list.

The results of the previous code are shown in the screenshot as follows:

Features selected based on an expression

In the next section, you will learn how to use the toolboxes that come with QGIS to execute algorithms and perform geospatial tasks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset