在 python 脚本中使用 QGIS 自定义函数

Using a QGIS Custom Function in a python script

我想为 python 中制作的 QGIS 使用自定义函数,并在 python 脚本中使用它。该函数来自这个答案 https://gis.stackexchange.com/questions/245146/getting-quantity-of-intersecting-lines-of-polygons-in-qgis 并且我更新了它以在 QGIS3 中工作(这并不难)。在我让它作为自定义函数工作后,我决定如果我能将它合并到脚本中会更好。我使用

将其放入 QGIS 的 python 控制台
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')

我得到了错误

TypeError: count_intersections() missing 2 required positional arguments: 'feature' and 
'parent'

我不确定如何处理特征参数和父参数或如何填充它们。我试过完全删除它们,但也没用。

如果我没理解错的话,你想要的是穿过网格每个单元格的线数。

你的错误意味着你需要 4 个参数来使用你的函数,网格层名称、线层、你计算相交线的网格特征和父参数。

最后一个参数与 PyQGIS 无关,但网格功能是必需的。我可以建议修改您的代码,这样您只需提供 2 个参数,层的名称。并在您的函数中获取网格功能,就像在这个片段中一样:

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')

我添加了一个循环来查看每个网格特征并将其与线特征进行比较。这将为每个单元格打印穿过单元格的行数。

PS:对于PyQGIS问题,我推荐你使用GISStackExcange