1

I need a tool which displays the sum of selected lines as I go in QGIS. Something like the Measure line-tool. I´m new to PyQGIS. The logic seems quite simple, I just don´t know where to start. I guess this could be a good starting point https://gis.stackexchange.com/a/211162/161290?

  • 2
    Since you post a link to the answer to your question, will you close your question yourself? Or will you describe, how that answer doesn't suite your needs? – Erik Apr 8 at 8:11
  • 1
    That´s an old answer and to my knowledge there has been changes in the API. I do not know what changes need to be made to the code to make it work. The linked answer does not work as it is. Thank you. – Topi V Apr 8 at 8:38
1

A possible solution is using the Field Calculator to create a label that show the sum of the selected lines.

In the lines layer create a label using the expression

array_sum(aggregate(
 layer:= 'line',
 aggregate:='array_agg',
 expression:=$length,
 filter:=is_selected()))

NB: To use array_sum in the oldest QGIS versions you need to install the plugin arrayPlus.

This will create a label with the sum of the selected lines. It will appear in all the lines.

Since QGIS 3.10 in the label is integrated a Geometry Generator: you can use it to move the label to the centre of the screen or in a preferred position.

In the Layer Styling > Label Panel go to the Geometry Generator and use the variable

@map_extent_center and select the Point / Multipoint geometry option

this will move a single label to the centre of you Canvas. enter image description here

If you want you can play with colour , background and offset to move your label. This is an example integrating the original expression with a text.

Here the modified expression:

concat( 'Total length: ',
array_sum(aggregate(
 layer:= 'line',
 aggregate:='array_agg',
 expression:=(format_number($length,3)),
 filter:=is_selected()))
,' m')

enter image description here

| improve this answer | |
  • There is no function named array_sum. Which version are you using? Otherwise this is exactly the solution I'm looking for. – Topi V Apr 8 at 9:53
  • I am using 3.10. Sorry, my bad. To use array_sum you need to install the plugin ArrayPlus that integrated some extra array to your system. I will correct the answer. – Val P Apr 8 at 9:56
  • Everything's working now. Thank you so much! – Topi V Apr 8 at 10:01
  • You're welcome. If you are happy with the answer can you please vote and accept it. Thanks. – Val P Apr 8 at 10:29

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.