I'm working with a layer in QGIS (v3.40) that uses a Raster Image Marker as its symbol. In the layer's symbology, I explicitly set:
- Width (Largeur):
100
pixels - Height (Hauteur):
50
pixels - Unit:
Pixels
Here's what it looks like in the GUI: Raster Layer Marker I want to retrieve the actual width and height using PyQGIS, and I'm using the following code:
layer = iface.activeLayer()
symbol = layer.renderer().symbol()
symbol_layer = symbol.symbolLayer(0)
print("size():", symbol_layer.size())
However, according to the QgsMarkerSymbolLayer documentation, the size function only returns a float, mainly the width (to be confirmed)
Is there a way to get those dimensions?
1 Answer 1
I'm not sure if this is exactly what you are after but maybe you could use this approach which involves retrieving the symbol rendered for each feature. This piece of code just prints width & height for any unique symbol dimensions found during the iteration at the end (which should only be one in your case) but if you were using data-defined overrides for symbol size, you could print the width, height & units for each feature separately in the feature iterator loop.
Due to time constraints I put this answer together fairly quickly so the code could be refined/improved but should give you an adequate starting point.
layer = iface.activeLayer()
renderer = layer.renderer().clone()
map_settings = iface.mapCanvas().mapSettings()
render_context = QgsRenderContext().fromMapSettings(map_settings)
expression_context = render_context.expressionContext()
context_scope = QgsExpressionContextScope()
context_scope.setFields(layer.fields())
expression_context.appendScope(context_scope)
sym_sizes = []
size_unit = None
renderer.startRender(render_context, layer.fields())
for feat in layer.getFeatures():
expression_context.setFeature(feat)
sym = renderer.symbolForFeature(feat, render_context)
size_unit = sym.sizeUnit()
point_f = feat.geometry().asQPointF()
sym_bounds = sym.bounds(point_f, render_context, feat)
#print(sym_bounds)
sym_sizes.append((sym_bounds.width(), sym_bounds.height()))
renderer.stopRender(render_context)
symbol_sizes = list(set(sym_sizes))
for i in symbol_sizes:
print(f"Width:{i[0]} {Qgis.RenderUnit(size_unit).name}")
print(f"Height:{i[1]} {Qgis.RenderUnit(size_unit).name}")
-
Honestly, your code seems a bit over-engineered. I expected a more straightforward way to obtain the width and height from the symbology configuration. Thank you for your assistance.Jacob C.– Jacob C.2025年07月29日 13:23:52 +00:00Commented Jul 29 at 13:23
QgsRasterMarkerSymbolLayer
object, seesymbol_layer.properties()