2

I wan't to sort a QGIS categorized symbol renderer by label name with PyQGIS. First i create categories and after i apply them to my layer but how to make an ascending alphabetic order on categorie's name ?

Documentation explain we can sort categories by their label with .sortByLabel().

I'm using QGIS3.10.2.

# Categories
categories = []
for myAttrName, (color, label, contour) in myStyleDict.items():
    symbol = QgsFillSymbol.defaultSymbol(myLayer.geometryType())
    symbol.setColor(QColor(color))
    symbol.symbolLayer(0).setStrokeWidth(0.26)
    symbol.symbolLayer(0).setStrokeColor(QColor(contour))
    category = QgsRendererCategory(myAttrName, symbol, label)
    categories.append(category)

# Renderer
expression = 'myAttrField'
renderer = QgsCategorizedSymbolRenderer(expression, categories) 
#renderer = QgsCategorizedSymbolRenderer(expression, categories).sortByLabel() ?  
myLayer.setRenderer(renderer)

1 Answer 1

2

This post give a good answer with a clause applied on the renderer. To complete my previous post, I add this after the .setRenderer :

renderer.setOrderBy(QgsFeatureRequest.OrderBy([QgsFeatureRequest.OrderByClause(expression, False)]))
renderer.setOrderByEnabled(True)

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.