【问题标题】:Selecting and manipulating multiple features using the QgsFeatureRequest().setFilterExpression() function in PyQGIS使用 PyQGIS 中的 QgsFeatureRequest().setFilterExpression() 函数选择和操作多个特征
【发布时间】:2020-02-06 16:29:35
【问题描述】:

我有一个矢量图层,其中包含一个名为“类型”的属性字段。我正在尝试删除“类型”值不是“主要”的所有功能。这是我的小脚本,感谢herehere 的回答:

from qgis.core import *
with edit(layer):
    request = QgsFeatureRequest().setFilterExpression("\"type\" != 'primary'")
    request.setSubsetOfAttributes([])
    request.setFlags(QgsFeatureRequest.NoGeometry)   
    selection = layer.getFeatures(request)
    layer.deleteFeatures([f.id() for f in selection])

但是,当我运行它时,什么也没有发生。我已经确定我使用的是正确的图层

>>>layer.id()

由于没有错误,我假设我的过滤器表达式格式不正确。可能是这种情况,还是我的脚本逻辑有问题?我在 QGIS 3.4.12 上运行 Python 3.7.0。

【问题讨论】:

    标签: python qgis


    【解决方案1】:

    您的过滤器表达式似乎工作正常。但对 deleteFeatures() 的调用仅对已通过调用 startEditing() 启用编辑的图层有效。在调用 commitChanges() 之前,使用此方法对功能所做的更改不会提交给底层数据提供者。任何未提交的更改都可以通过调用 rollBack() 来丢弃。

    layer.startEditing()
    layer.deleteFeatures([f.id() for f in selection])
    layer.commitChanges()
    

    请参考文档 Oficial Documentation

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 2016-01-24
      • 1970-01-01
      • 2018-05-03
      • 2020-07-31
      • 1970-01-01
      • 2021-07-26
      • 2014-12-06
      • 2022-01-19
      相关资源
      最近更新 更多