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()
underdark
  • 84,148
  • 21
  • 231
  • 413
Kewitschka
  • 207
  • 1
  • 7

1 Answers1

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()
Kewitschka
  • 207
  • 1
  • 7