I have a problem when trying to label all features of a shapefile with a Python routine.
If I open my shapefile in QGIS "by hand", and select a .qml with pre-defined label selection, the labels are correctly displayed. If I load the .qml file via a Python routine (see line below), all style features (colors etc.) are there, EXCEPT for the labels. No idea why.
myLayer.loadNamedStyle("someStyle.qml")
Since the line above did not give me the desired labels, I tried to create a more extensive routine, see below.
myProvider = myLayer.dataProvider()
myLayer.startEditing()
for myFeat in myLayer.getFeatures():
#Some calculations in here...
#The variable "Some_Value" is what I'd like to use as label
Index_myLabelField=myLayer.fieldNameIndex("myLabelField")
Value_myField={myFeat.id():{Index_myLabelField:QVariant(Some_Value)}}
myProvider.changeAttributeValues(Value_myField)
myLayer.commitChanges()
myLayer.label().setLabelField(0,Index_myLabelField)
myLayer.label().labelField(0)
print myLayer.label().fieldValue(0,myFeat) #Returns the desired label string
#Create map renderer
mapRenderer = QgsMapRenderer()
rect = myLayer.extent()
mapRenderer.setExtent(rect)
mapRenderer.setLayerSet(QStringList(myLayer.id()))
myRenderContext = mapRenderer.rendererContext()
myLayer.select(myFeat.id())
print myLayer.isValid() #Returns true
myLayer.label().renderLabel(myRenderContext,myFeat,1) #Error: Segmentation fault (core dumped)
Until the last line, where I try to render the label, everything seems to work fine.
What is going wrong in the last line?
There are two things I am unsure about:
In the QGIS API, the function to tell QGIS the field I want to use as label is
setLabelField (int attr, int fieldIndex)
What is the "attr" in this context?
What should I put here?
I used "0" so far...
- In the renderLabel() function, there is a "bool selected" needed in third position of the call. So what I am doing is selecting the feature (myFeat), and telling the function a "1" here.
Is that correct?
Rendering and Labeling Shapefile with PyQGIS does not fully help me, as the OP there does not seem to label all features of his shapefile. I am able to add one label to the shapefile (kind of like a title) with the described method there, but I am looking to have a label next to every feature (e.g. like street names on a map).
If you know why the qml-loading in the beginning of my post does not work can you let me know?