I have some layers in my project and I would like to alter their styles, since ranges of values for underlying columns have changed.

Normally it would require to enter each layer style settings separately and trigger "Remove All", and "Classify" button, however I would like to execute it from the code.

I found such method for graduated symbol:


,however I'm having trouble to find corresponding method for categorized symbol class

Is there any way to do this from pyqgis without the need to specify the layer style from the scratch (create category, label etc.) ? Some equivalent of "Classify" button from below screenshot:

enter image description here


1 Answer 1


I found a workaround according to this answer to Applying catgorized symbol to each feature using PyQGIS, with some little correction in the 3rd line (layer.dataProvider().uniqueValues() to layer.uniqueValues())

# provide file name index and field's unique values
fni = layer.fieldNameIndex('EdgeRef')
unique_values = layer.uniqueValues(fni)

# fill categories
categories = []
for unique_value in unique_values:
    # initialize the default symbol for this geometry type
    symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())

    # configure a symbol layer
    layer_style = {}
    layer_style['color'] = '%d, %d, %d' % (randrange(0, 256), randrange(0, 256), randrange(0, 256))
    layer_style['outline'] = '#000000'
    symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style)

    # replace default symbol layer with the configured one
    if symbol_layer is not None:
        symbol.changeSymbolLayer(0, symbol_layer)

    # create renderer object
    category = QgsRendererCategoryV2(unique_value, symbol, str(unique_value))
    # entry for the list of category items

# create renderer object
renderer = QgsCategorizedSymbolRendererV2('EdgeRef', categories)

# assign the created renderer to the layer
if renderer is not None:


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