3

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

1 Answer 1

7

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.

4
  • 3
    You could also download the "expressions+" plugin, which includes a pre-built "is_selected" function
    – ndawson
    Commented Aug 10, 2015 at 21:59
  • @ndawson - thanks for that, hadn't come across that before.
    – Steven Kay
    Commented Aug 10, 2015 at 22:10
  • @ndawson - I've downloaded the plugin, but don't know how to use it, and I can't find any instructions. Would you please advise? Thanks!
    – Stu Smith
    Commented Sep 27, 2015 at 19:55
  • Comments aren't really the place for questions, but see my answer in: gis.stackexchange.com/questions/111784/… and put the expression into the Rendering>Label options> Data defined> Show label
    – HeikkiVesanto
    Commented May 31, 2017 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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