The idea: use virtual fields
To restrict the creation of lines to lines with start- and end points snapped to existing vertices, create a virtual field (updated whenever you add a feature) that checks if start- and endpoint are on a line segment. Then you have two options:
Set "hard" restraints - adding an unconnected line is not possible. Only lines connected at start- and endpoint will be added.
No restraints for adding lines, but unconnected lines will be highlighted visually until you connect them - this gives you a visual control where there are unconnected lines left and allows for a more intuitive workflow.
Virtual field: the principles
For both options, first create a virutal field (then it is updated every time you add a feature). This field tests if the start-point is connected to a line. Name the field as start
, set field type to boolean. Repeat the same for the end-point, creating a virtual field end
.
Use the following expression for the startpoint (at the beginning of line two replace start_point
with end_point
to create field end
):
intersects(
start_point ($geometry),
difference (collect ($geometry), $geometry)
)
Option 1: Setting hard restraints using constraints
Go to Layer Properties / Attributes Form
and select the virtual fields. For Constraints
, set (again) the expression from above for start- and end field. Be sure to check the box Enforce expression constraint
.
Now, you won't be able any more to add unconnected lines. Only fully connected lines will be accepted.
Setting the constraints:
Unconnected ends: you can't add the feature, OK
button is grayed out:
Option 2: Visual control of unconnected features
Style the lines differently based on the result of that field. Like this, you have a visual control where there are unconnected lines left and you can connect them.
Set the layer's style to Rule-based
and add two rules, one for "start" = true and "end" = true
(both points connected to the network: green), the other for "start" = false or "end" = false
(one or both points not connected to the network: red).
Now, you can visually recognize which lines are connected and which ones are not. Connecting unconnected lines changes their visual style as you can see in this screencast:
Red: unconnected lines; green: connected lines. If unconnected lines are connected, their style changes. That gives a visual control of where there are unconnected lines and helps you to intuitively complete the lines: