[GIS] Label only selected features using QGIS

featureslabelingqgisqgis-custom-functionselect

Is it possible to make an expression that labels only the selected feature in QGIS? I tried it with this expression in the label tab:

attribute( $currentfeature, 'LAENGE' )

but it labels all and not only the selected:

enter image description here

Best Answer

Yes, it's possible, using the new Python function editor in 2.8 or later. For a good tutorial check out this youtube video

Your existing expression will always show the value of field "LAENGE" for all features, this is working as expected.

What you really want is an $is_selected() function which evaluates to True if the feature is selected, or False if it isn't.

Create a python function like this, and name it 'is_selected'

from qgis.core import *
from qgis.gui import *
from qgis.utils import *

@qgsfunction(args=0, group='Python')
def is_selected(values,feature,parent):
    layer = qgis.utils.iface.activeLayer()
    return feature.id() in layer.selectedFeaturesIds()

You can now dynamically add labels to only those features which are selected (it will slow down rendering, though, so be careful if you have lots of polygons)

Here's an example, I've labelled each polygon with the value of is_selected()

enter image description here

You should now be able to use this in a CASE statement to only label the selected features.

Might want to check out When iterating over a vector layer with pyqgis, how do I check whether a feature is selected?, which I found useful in working this out.

Related Question