5

I have a number of points that I'm visualising on a points layer, and labelling using PyQGIS. Unfortunately when zoomed out too much, the resultant map appears a mess of labels.

Can I use PyQGIS to specify that labels should only appear in certain circumstances? I was hoping to test with displaying labels:

  • Only if there are less than a certain number of points currently being rendered/visible on the screen (e.g. 50) - I suspect this is the best solution
  • Failing that, set to only display labels if the scale is less than 1:5000*

Is it possible to do either of the above using PyQGIS?

Edit: * I can do this manually in QGIS by enabling: Rendering > Label options > Scale dependent visibility and setting min/max scale values

Current code is along the lines of:

layer_settings = QgsPalLayerSettings()
layer_settings.drawLabels = True
layer_settings.fieldName = "Vehicle"
layer_settings.isExpression = True

label_settings = QgsVectorLayerSimpleLabeling(layer_settings)

points_layer.setLabeling(label_settings)
points_layer.setLabelsEnabled(True)
1
  • You could try to use the QGIS point cluster renderer. – christoph Sep 1 '20 at 15:25
5

Use scaleVisibility and minimumScale attributes of QgsPalLayerSettings class.

# other stuff

layer_settings.scaleVisibility = True
layer_settings.minimumScale = 5000 # -> 1:5.000

#...

Also you can set maximum scale using layer_settings.maximumScale = 5000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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