1

I have a layer with cities. I want to set a different color for a specific country. I can iterate through all cites (features) and change the color of ALL features but not only of single ones. How can I achieve that?

from PyQt4.QtCore import *
from PyQt4.QtGui import *

#Get layer
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "cities_min":
        layer = lyr
        break

#Iterate features. How to set color of single features
for f in layer.getFeatures():
    print f['name'],f['country_code']
    if f['country_code']=='GB':
        #Set Color
        break

#Apply color to ALL features
symbols = layer.rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QColor('yellow'))
layer.triggerRepaint()
1

1 Answer 1

1

I solved it as followed:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

#Get layer
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "cities_min":
        layer = lyr
        break

#Set selection color
iface.mapCanvas().setSelectionColor( QColor("red") )

#filter features to select
expr = QgsExpression( "\"country_code\"='DE'" )
it = layer.getFeatures( QgsFeatureRequest( expr ) )
ids = [i.id() for i in it]
layer.setSelectedFeatures( ids )
layer.triggerRepaint()

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.