Sunday, 7 October 2018

pyqgis - Connecting vector label size with map-units?


I have a working application of labels to a point array - but the size of the text is not relative to the map scale. This decreases the readability of labels when panning and zooming.


To resolve~



How would one implement a text-size based on MapUnits?


    field = str(csvGridFieldNames[index])
csvGrid = ftools_utils.getMapLayerByName(unicode('mfLayer1_Grid'))#str(activeLayer)))
textSize = 7
valLabel = QgsPalLayerSettings()
valLabel.readFromLayer(csvGrid)
valLabel.enabled = True
valLabel.fieldName = field
valLabel.placement= QgsPalLayerSettings.OverPoint
valLabel.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'%f' %(textSize),'')

valLabel.writeToLayer(csvGrid)
iface.legendInterface().refreshLayerSymbology(csvGrid)
iface.mapCanvas().refresh()

This question appears related, but having some trouble understanding the doc's...


"...lables 'Data Defined' section in pyqgis"


...and FWIW:


A screen shot of the Qgis tool, with the two (needed) PyQgis settable parameters highlighted in green: lable settings


Updates following underdark's advice:


Input syntax errors (on my part) are not raising error flags - but are also not implementing MapUnit based font/label size...



    valLabel.SizeUnit = QgsPalLayerSettings.MapUnits
valLabel.setDataDefinedProperty(QgsPalLayerSettings.FontSizeUnit,True,True,':%f' %(textSize),'')

LAST UPDATE [SOLVED] (final working code below):


    textSize = (abs(scale[0]-scale[1]))/4
valLabel = QgsPalLayerSettings()
valLabel.readFromLayer(csvGrid)
valLabel.enabled = True
valLabel.fontSizeInMapUnits = True
valLabel.fieldName = field

valLabel.placement = QgsPalLayerSettings.OverPoint
valLabel.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'%f' %(textSize),'')
valLabel.writeToLayer(csvGrid)
iface.legendInterface().refreshLayerSymbology(csvGrid)
iface.mapCanvas().refresh()

Answer



Works for me:


valLabel=QgsPalLayerSettings()
valLabel.readFromLayer(iface.activeLayer())
valLabel.fontSizeInMapUnits=True // change to map units

valLabel.textFont.setPointSize(100000) // set font size
valLabel.writeToLayer(iface.activeLayer())
iface.mapCanvas().refresh()



For the data-defined way check QgsPalLayerSettings::DataDefinedProperties FontSizeUnit


and enum QgsPalLayerSettings::SizeUnit



Units used for option sizes, before being converted to rendered sizes.


Enumerator



Points
MM
MapUnits
Percent



No comments:

Post a Comment