I'm trying to set the color of a vectorlayer feature depending on the feature attributes with PyQGIS.

How do you acces the attributes of a vectorlayer feature?


2 Answers 2


To set the color of a vector layer feature depending on the feature attributes with PyQGIS is necessary to change the QgsSingleSymbolRendererV2 default object in a, for example, QgsGraduatedSymbolRendererV2 object. To test this I created the 'random' field name in a Polygon Vector Layer and this field was filled with aleatory values between 1 and 24. These values were grouped in three arbitrary classes in a tuple for being used in the following code at the Python Console of QGIS:

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

layer = iface.activeLayer()

# define ranges: label, lower value, upper value, color name
# in the field named 'random' (attributes table) 
values = (
    ('Low', 1, 8, 'green'),
    ('Medium', 9, 16, 'yellow'),
    ('Large', 17, 24, 'orange'),

# create a category for each item in values
ranges = []
for label, lower, upper, color in values:
    symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    rng = QgsRendererRangeV2(lower, upper, symbol, label)

# create the renderer and assign it to a layer
expression = 'random' # field name
renderer = QgsGraduatedSymbolRendererV2(expression, ranges)


Before running the code at Python Console:

enter image description here

After running the code at the Python Console:

enter image description here

The renderer produced was of the QgsGraduatedSymbolRendererV2 type.


Right click on the layer in the table of contents > properties > style tab > there you have options to style as a single symbol, using categories, using graduated colours, and rules.

You then have the option to choose the field containing the values to be displayed.

See the QGIS manual for more information: http://docs.qgis.org/user_guide/html/en/

  • 2
    The OP is looking for a way to doing this using pyqgis which is the QGIS Python API, not via the GUI
    – Nathan W
    Aug 20, 2012 at 10:37
  • I realise that now after getting a mark down for my "answer" :-P Aug 20, 2012 at 13:31
  • Although technically not an answer to the question, this answer was very useful to me. Note that in recent versions you want to do a right-click on the layer in the layers list, then select the 'Symbology' tab. Then select 'Categorized' in the top dropdown. Select a column, then click 'Classify' near the bottom.
    – Kit
    Feb 11, 2019 at 11:27

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.