Some small python script you can use:
- Access the layers
- Set a threshold (your source layers need to be in the same unit). The value needs to be big enough.
- Extend lines using
native:extendlines
- Clip the overlapping using
native:clip
- Add the layer to the map
- Filter all multipart segments which may intersect a second time with the polygon
from qgis import processing
# Load layers
blue_lines = QgsProject.instance().mapLayersByName("blue_lines")[0]
green_polygon = QgsProject.instance().mapLayersByName("green_polygon")[0]
# Set distance value
distance = 5000
# Extend Lines
temp_layer1 = processing.run("native:extendlines", {
'INPUT' : blue_lines,
'OUTPUT' : 'TEMPORARY_OUTPUT',
'START_DISTANCE' : distance,
'END_DISTANCE' : distance
})['OUTPUT']
# Clip
resultLayer = processing.run("native:clip", {
'INPUT' : temp_layer1,
'OUTPUT' : 'TEMPORARY_OUTPUT',
'OVERLAY' : green_polygon
})['OUTPUT']
# Iterate over all features and remove multiparts
resultLayer.startEditing()
for feature in resultLayer.getFeatures():
# Create a multi_polyline from the geometry of each feature
multi_polyline = feature.geometry().asMultiPolyline()
# Iterate over each multi polyline segment so we can find the correct ones
for polyline in multi_polyline:
# Create a temorary geometry
geom = QgsGeometry.fromPolyline([QgsPoint(x) for x in polyline])
# Iterate over all blue line features
for blue_lines_feature in blue_lines.getFeatures():
# Create a small buffer around the segment
# and see if any of the blue line geometries is totaly within
if blue_lines_feature.geometry().within(geom.buffer(1,5)):
# If it is within update the geometry
resultLayer.dataProvider().changeGeometryValues({feature.id(): geom})
resultLayer.commitChanges()
QgsProject.instance().addMapLayer(resultLayer)
Update:
If your polygon has sharp turns it's better to identify the correct multipart element by creating a small buffer around the extended lines so we can check which blue lines are 100% within those buffers. Those segments are kept within the result layer.
