7

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:

renderer.updateClasses(layer,0,bins)

,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

6

I found a workaround according to https://gis.stackexchange.com/a/175114/107021 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
    categories.append(category)

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

# assign the created renderer to the layer
if renderer is not None:
    layer.setRendererV2(renderer)

layer.triggerRepaint()
  • 1
    Just because I stumbled upon: from random import randrange – Eva Großmann Mar 26 '18 at 12:37

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.