3

I am trying to generate a proportional symbol symbology using data defined symbol size in a QGIS 3 python plugin.

Here is the working code :

# Symbol creation
symbolLayer = QgsSimpleMarkerSymbolLayer()
symbolLayer.setShape(QgsSimpleMarkerSymbolLayer.Circle)
symbolLayer.setSize(2.0)
symbolLayer.setColor(QColor(31, 120, 180)
symbolLayer.setStrokeColor(QColor(255, 255, 255)
symbolLayer.setStrokeWidth(0.4)

symbol = QgsMarkerSymbol.createSimple({})
symbol.changeSymbolLayer(0, symbolLayer)

# Size definition (Flannery method)
# layer is a QgsSingleSymbolRenderer
strExp = 'coalesce(scale_exp("value", 0.0, 150, 1, 20, 0.57), 0)'
symbol.setDataDefinedSize(QgsProperty.fromExpression(strExp))
layer.renderer().setSymbol(symbol)

The problem is the legend. This code :

# Legend
lgd = QgsDataDefinedSizeLegend()
lgd.setLegendType(QgsDataDefinedSizeLegend.LegendCollapsed)
lgd.setClasses([
    QgsDataDefinedSizeLegend.SizeClass(150, '150'),
    QgsDataDefinedSizeLegend.SizeClass(75, '75'),
    QgsDataDefinedSizeLegend.SizeClass(15, '15')
])

layer.renderer().setDataDefinedSizeLegend(lgd)

produces an enormous legend symbol :

wrong legend

However, if I open the layer properties dialog and update parameters with datadefined size assistant, the legend is refreshed with the correct size :

correct legend

What am I missing ?

3
  • 1
    I've got the same problem, but I didn't any answer at this time Feb 12, 2019 at 16:45
  • 1
    I have not tried it but you can add this iface.layerTreeView().refreshLayerSymbology(layer.id())
    – Fran Raga
    Feb 12, 2019 at 19:18
  • I have this line allready...
    – sigeal
    Feb 12, 2019 at 19:38

1 Answer 1

1

first of all as you are working on QGIS 3, the way you define the size is not wrong but now there's a class which allows to do this directly:

objTransf = QgsSizeScaleTransformer(
        QgsSizeScaleTransformer.Flannery,
        0,
        150,
        0,
        150,
        0,
        0.57)

you'll find more about this class here:

QgsSizeScaleTransformer

you have to create a QgsProperty, set its Field to strFieldName, set its transformer to objTrans and send it as the dataDefinedSize of your symbol.

objProp = QgsProperty()
objProp.setField(strFieldname)
objProp.setTransformer(objTransf)
symbol.setDataDefinedSize(objProp)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.