Programmatically changing line lengths in QGIS?

You can do this with expressions, creating new attribute table columns and then creating a line from the coordinates.

First create four new columns using the expression engine in the attribute table editor. The names and expressions are below, depending on a numeric attribute called outlen which is how long you want the output lines to be. If you want them to all be 1km or whatever put that constant in place in the expressions. Make sure you create "Decimal Number" (and not integer) attributes. Here's one:

enter image description here

here's the name and expression for all four - cut and paste each expression into the box - the differences are subtle:

x0: x(centroid($geometry)) - 
    (outlen/2) * sin(radians(angle_at_vertex($geometry, 0)))
y0: y(centroid($geometry)) - 
    (outlen/2) * cos(radians(angle_at_vertex($geometry, 0)))
x1: x(centroid($geometry)) + 
    (outlen/2) * sin(radians(angle_at_vertex($geometry, 0)))
y1: y(centroid($geometry)) + 
    (outlen/2) * cos(radians(angle_at_vertex($geometry, 0)))

With that done, your attribute table should now look like this:

enter image description here

The lines you want to create go from (x0,y0) to (x1,y1).

Then use the expression editor one final time to update the <geometry> "field" to this:

 geom_from_wkt(format('LINESTRING (%1 %2) (%3 %4)',"x0","y0","x1","y1"))

when you save the changes, your lines should all have changed length! Work on a copy if you need the original!


QGIS 3.2

Another option is extend() function which is available in QGIS 3.2.

If you have two attribute fields:

  • len1: original length (m)
  • len2: target length (m)

Then the expression would be extend($geometry, ("len2"-"len1")/2, ("len2"-"len1")/2 )


[Usage] Select Update existing field and then <<geometry>>

enter image description here


Just for the sake of documenting: After Kazuhito's answer I realized that there is an algorithm in the processing toolbox called Extend lines which seems to do what I wanted to achieve (visit documentation here):

enter image description here

When used within the graphical modeller, the Start distance and End Distance parameters can be calculated using Field calculator, hence being able to add a formula like Kazuhito's.

Unfortunately, this does not solve my problem since I want to be able to extend lines (works great) but also shrink them (lines cannot be shrunk). I have created the following issue but currently has been rejected (hope developers reconsider their position)

PS: all credits go for @Kazuhito