[GIS] Specifying Minimum and Maximum Word Wrap length in QGIS

labelingqgis

I want my labels to fit nicely within polygons.

Based on this answer to Creating multiline labels in QGIS, I discovered the power of the wordwrap function in QGIS to make labels. However, I'm confused as to how I could specify a minimum AND a maximum length for wrapping: I'd like no line to be longer than say 13 characters, but I also don't want any line to only have 3 characters. Merely nesting the functions didn't work out for me

wordwrap( wordwrap( title(SITE_NAME) , -3), 13)

So I would like this label to fit someone nicely within its polygon
enter image description here

But if I only use the simple wordwrap it looks ridiculous.
enter image description here

And if I try to build an expression for wordwrap, e.g. wordwrap( title("SITE_NAME") , -3), the "output preview" shows

'Anthony
A. Loconte
Memorial
Skating
Rink'

But the result is still the first image above.

But if I instead put wordwrap( title("SITE_NAME") , -3) in the Label With box (and make sure to disable all wordwrap functions. I get:
enter image description here

Best Answer

From the help section for wordwrap()

If wrap_length is positive the number represents the ideal maximum number of characters to wrap

The key word being ideal ... wordwrap() wont break a 15 char word down at the 13th character.


EDIT: The function below needs further refinement for the sample string provided.

'Anthony A. Loconte Memorial Skating Rink'

This function will inject a specified delimiter at the max number specified:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def MaxWrap(inField, maxn, delim, feature, parent):
    return delim.join([inField[i:i+maxn] for i in range(0, len(inField), maxn)])

Then use wordwrap with the same delimiter and your minimum:

wordwrap(maxwrap( SITE_NAME, 13, '^-^'), -3, '^-^')
Related Question