First of all you need to construct your QgsSvgMarkerSymbolLayer with parameters, a dictionnary
with the path
and other caracteristics such as size
or color
. For the QgsRenderCategory you need to specify the value
, the QgsSymbol
and then the string
. Depending on the type of your layer I give you two snippets of code that should work.
My answer is based on the answer of the post Automatic pyqgis categorized renderer classification [duplicate] by fuzzysolutions
If your layer is a point layer :
values = {"existante", "potentielle"}
categories = []
for value in values:
svgStyle = {}
svgStyle['fill'] = '#000000'
if value == "existante" :
svgStyle['name'] = path + "bloc1_typologieB.svg"
elif value == "potentielle" :
svgStyle['name'] = path + "bloc1_typologieR.svg"
svgStyle['outline'] = '#000000'
svgStyle['outline-width'] = '0.3'
svgStyle['size'] = '7'
statut = QgsSvgMarkerSymbolLayer.create(svgStyle)
symbol = QgsSymbol.defaultSymbol(gares_asof0305.geometryType())
symbol.appendSymbolLayer(statut)
category = QgsRendererCategory(value, symbol, str(value))
categories.append(category)
renderer = QgsCategorizedSymbolRenderer('situation', categories)
# assign the created renderer to the layer
if renderer is not None:
gares_asof0305.setRenderer(renderer)
gares_asof0305.triggerRepaint()

if your layer is a polygon layer :
values = {"existante", "potentielle"}
categories = []
for value in values:
svgStyle = {}
svgStyle['fill'] = '#000000'
if value == "existante" :
svgStyle['name'] = path + "bloc1_typologieB.svg"
elif value == "potentielle" :
svgStyle['name'] = path + "bloc1_typologieR.svg"
svgStyle['outline'] = '#000000'
svgStyle['outline-width'] = '0.3'
svgStyle['size'] = '7'
statut = QgsSvgMarkerSymbolLayer.create(svgStyle)
symbol = QgsSymbol.defaultSymbol(gares_asof0305.geometryType())
centroid_symbol = QgsCentroidFillSymbolLayer.create()
centroid_symbol.setColor(QColor("transparent"))
colorP = QtGui.QColor(255, 255, 255, 255)
marker_symbol = QgsMarkerSymbol()
marker_symbol.changeSymbolLayer(0, statut)
centroid_symbol.setSubSymbol(marker_symbol)
symbol.appendSymbolLayer(centroid_symbol)
category = QgsRendererCategory(value, symbol, str(value))
categories.append(category)
renderer = QgsCategorizedSymbolRenderer('situation', categories)
# assign the created renderer to the layer
if renderer is not None:
gares_asof0305.setRenderer(renderer)
gares_asof0305.triggerRepaint()
