1

I'm trying to label only selected features with an expression using PyQgis and the PAL functions, but I don't find any example and the API don't help me a lot (or I don't found it). My Qgis version is 2.14

This is an extract of my code:

from PyQt4.QtGui import QColor
layer = iface.activeLayer()
palyr = QgsPalLayerSettings()
palyr.readFromLayer(layer)
palyr.enabled = True 
palyr.bufferDraw= True
palyr.bufferColor= QColor("white")
palyr.bufferSize = 1
palyr.scaleVisibility = True
palyr.scaleMax=2000
palyr.isExpression = True
# code is a fieldname. Only show the last 3 letters
palyr.fieldName = 'right( code ,3 )'   
palyr.size = 20
# next 2 lines is for change placement 
palyr.placement= QgsPalLayerSettings.OverPoint 
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','') 

# I want to set this expression for label only selected features:  "code not like '%000'" 
# MISSING CODE FOR SET DEFINED LABEL USING EXPRESSION 

palyr.textColor = QColor("red")
palyr.drawLabels = True
palyr.writeToLayer(layer)
iface.mapCanvas().refresh()

I can run this code without errors, but I don't know how to set expression for defined data features.

1

I answer me myself. I don't like, but I only found this solution: I have used conditional function in label expression. "if" has 3 arguments (condition, label if true, label if not)

This is the correct code

from PyQt4.QtGui import QColor
layer = iface.activeLayer()
palyr = QgsPalLayerSettings()
palyr.readFromLayer(layer)
palyr.enabled = True 
palyr.bufferDraw= True
palyr.bufferColor= QColor("white")
palyr.bufferSize = 1
palyr.scaleVisibility = True
palyr.scaleMax=2000
palyr.isExpression = True
# CONDITIONAL EXPRESSION
palyr.fieldName =   'if( "code" NOT LIKE \'%000\', right(  "code" ,3),"")'
# OLD: palyr.fieldName = 'right( code ,3 )'       
palyr.size = 20
palyr.placement= QgsPalLayerSettings.OverPoint 
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','') 
palyr.textColor = QColor("red")
palyr.drawLabels = True
palyr.writeToLayer(layer)
iface.mapCanvas().refresh()

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.