I want to take a custom function for QGIS made in python and use it in a python script. The function came from this answer https://gis.stackexchange.com/questions/245146/getting-quantity-of-intersecting-lines-of-polygons-in-qgis and I updated it to work in QGIS3 (that wasn't hard). After I got it working as a custom function I decided it would be better if I could incorporate it in a script. I put this into the python console in QGIS using
def count_intersections(grid_layer_name, line_layer_name, feature, parent):
grid_layer = QgsProject.instance().mapLayersByName( grid_layer_name )[0]
line_layer = QgsProject.instance().mapLayersByName( line_layer_name )[0]
count = 0
for line_feat in line_layer.getFeatures():
if feature.geometry().intersects(line_feat.geometry()):
count = count + 1
return count
print(count_intersections('Grid', 'line')
And I get the error
TypeError: count_intersections() missing 2 required positional arguments: 'feature' and
'parent'
I'm not sure what to do with feature and parent parameters or how to fill them. I tried removing them completely but that didn't work either.
If I understand correctly, you want the number of line crossing every cell of a grid.
Your error means that you need 4 arguments to use your function, the grid layer name, the line layer, the feature of the grid where you are counting the intersecting lines and the parent argument.
The last argument is not relevant for PyQGIS but the grid feature is mandatory. I can propose to modify your code so you only have to give 2 arguments, the layers' name. And get the grid feature inside your function like in this snippet :
def count_intersections(grid_layer_name, line_layer_name):
grid_layer = QgsProject.instance().mapLayersByName( grid_layer_name )[0]
line_layer = QgsProject.instance().mapLayersByName( line_layer_name )[0]
for feature in grid_layer.getFeatures(): # added loop
count = 0
for line_feat in line_layer.getFeatures():
if feature.geometry().intersects(line_feat.geometry()):
count = count + 1
print(count)
count_intersections('Grid', 'Line')
I added a loop to look through each grid feature and compare it with line features. This is going to print for each cell the number of lines which cross the cell.
PS: For PyQGIS question, I recommend you to use GISStackExcange.