2

I'm trying to generate categorized symbols for a polygon layer in QGIS 3.4. The code below should generate random colour polygons for each record of 'run' layer and I'm not getting any error message. The layers toolbar shows the coloured categories created, but the 'run' layer is not visible at all.

    ls = QgsProject.instance().layerStore()
    r_layer = ls.mapLayersByName('run')[0]

    # get unique values
    fni = r_layer.fields().indexFromName('id')
    unique_ids = r_layer.dataProvider().uniqueValues(fni)
    QgsMessageLog.logMessage("sstyle for run layer..." + str(unique_ids))
    # define categories
    categories = []
    for unique_id in unique_ids:
        # initialize the default symbol for this geometry type
        symbol = QgsSymbol.defaultSymbol(r_layer.geometryType())
        symbol.setOpacity(0.5)

        layer_style = {}
        layer_style['color'] = '%d, %d, %d' % (randrange(0, 256), randrange(0, 256), randrange(0, 256))
        layer_style['outline'] = '#000000'
        symbolLayer = QgsSimpleFillSymbolLayer.create(layer_style)

        if symbolLayer is not None:
            symbol.changeSymbolLayer(0, symbolLayer)
        category = QgsRendererCategory(unique_ids, symbol, str(unique_id))
        categories.append(category)

    renderer = QgsCategorizedSymbolRenderer('id', categories)
    # assign the created renderer to the layer
    if renderer is not None:
        r_layer.setRenderer(renderer)
    r_layer.triggerRepaint()
2

There's a typo in your script. Instead of:

category = QgsRendererCategory(unique_ids, symbol, str(unique_id))

you need:

category = QgsRendererCategory(unique_id, symbol, str(unique_id))

(i.e. "unique_id" instead of the list of all "unique_ids")

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.