3
layer = iface.activeLayer()

# get unique values for 'severity' field
fni = layer.fieldNameIndex('severity')
unique_vals = layer.dataProvider().uniqueValues(fni)

# define categories to use in symbology
categories = []

for val in unique_vals:
    # initialise 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)
    else:
        print "success"

    # create renderer object
    category = QgsRendererCategoryV2(val, symbol, str(val))
    # entry for the list of category items
    categories.append(category)

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

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

layer.triggerRepaint()

I have used this post, and copied the code above in to the python console. It appears to work fine, as I end up with the correct number of categories, i.e. 1 for every unique value in my chosen attribute, however after categories.append(category) it prints out False for every iteration of the loop. End result is fine though, so would anyone be able to explain why it's printing out False?

I thought it might have been if symbol_layer is not None: etc. but I added an else: print "success" and it's not doing that so doesn't look like that's the issue. Like I said, it does work but I'm curious

perhaps worth mentioning the layer I'm using is from a postgres database

0

1 Answer 1

2

after adding some print statements after each line I managed to work out that it's symbol.changeSymbolLayer(0, symbol_layer):

bool QgsSymbolV2::changeSymbolLayer( int index, QgsSymbolLayerV2* layer )
{
   QgsSymbolLayerV2* oldLayer = mLayers.value( index );

   if ( oldLayer == layer )
      return false;

   if ( !layer || !layer->isCompatibleWithSymbol( this ) )
      return false;

   delete oldLayer; // first delete the original layer
   mLayers[index] = layer; // set new layer
   return true;
}

link (line 429)

the layer is valid and since everything else works it must be if (oldLayer == layer) that's returning False. Also I only have 1 layer open

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.