A labeling routing (which is updated often) is being implemented via pyqgis and a QComboBox.
The code below worked great, that is until needs for narrowed column headers spawned the use of pythons '\n' (and subsequent problems thereafter).
This string formatting switch has caused any multiline field reference to return blank labels, while neighboring fields with single lines are displayed correctly.
A remedy I initially sought was to use fieldname (as strings) for the label settings, but this did not work. Then it was supposed that a index based context would work better (avoiding syntax), but such did not solve the problem
I am suspicious that I might be missing a line in my publishing of the QgsPalLayerSettings() class to the layer. Because when I do it manually through the QGIS labeling menu, multiline field names work perfectly fine.
Related to a previous question: Connecting vector label size with map-units?
field = str(self.csvGridFieldNames[index])
activeLayerName = self.iface.activeLayer().name()
csvGrid = ftools_utils.getMapLayerByName(unicode(activeLayerName))
# fieldIdx = csvGrid.fieldNameIndex(field)
textSize = 'coconut hoves'
valLabel = QgsPalLayerSettings()
valLabel.readFromLayer(csvGrid)
valLabel.enabled = True
valLabel.placement = QgsPalLayerSettings.OverPoint
valLabel.fieldName = field
# valLabel.fieldIndex = fieldIdx
valLabel.fontSizeInMapUnits = True
valLabel.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'%f' %(textSize),'')
valLabel.writeToLayer(csvGrid)
valLabel.writeToLayer(csvGrid)
iface.legendInterface().refreshLayerSymbology(csvGrid)
iface.mapCanvas().refresh()
For sake of missing information, the following is a list of a few fieldNames (as contained in the list 'self.csvGridFieldNames');
While 'Status' and 'Kx' publish labels correctly, both 'Top\nElevation','Bottom\nElevation' do not.
['Status','Top\nElevation','Bottom\nElevation','Kx']
Per advice, the following also does not work:
(And 'print repr(field)' returns expected 'Top\\nElevation')
rawField = str(self.csvGridFieldNames[index])
if '\n' in rawField:
beginingOfString,endOfString = rawField.split("\n")
field = beginingOfString+'\\n'+endOfString
else: field = rawField
valLable.wrapChar = '\\n' #<<=== with/without this line, still blank labels
Link to a ultra-beta QgsPointLayer Labeler pulled from a larger (yet unpublished) plugin. Extract contents to Qgis Python Plugins Dir as normal.
ReadMe instructions are a must for functionality.
valLabel.wrapChar = "\n"
valLabel.fieldName = "Top\\nElevation"
. I think it should work.