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?
-
2Since 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?– ErikApr 8, 2020 at 8:11
-
1That´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 VApr 8, 2020 at 8:38
1 Answer
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.
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')
-
There is no function named array_sum. Which version are you using? Otherwise this is exactly the solution I'm looking for.– Topi VApr 8, 2020 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 PApr 8, 2020 at 9:56 -
-
You're welcome. If you are happy with the answer can you please vote and accept it. Thanks.– Val PApr 8, 2020 at 10:29