简体   繁体   English

使用 PyQGIS 中的 QgsFeatureRequest().setFilterExpression() 函数选择和操作多个特征

[英]Selecting and manipulating multiple features using the QgsFeatureRequest().setFilterExpression() function in PyQGIS

I have a vector layer with an attribute field called "type".我有一个带有名为“type”的属性字段的矢量图层。 I am trying to delete all features whose value for "type" is not "primary".我正在尝试删除“类型”值不是“主要”的所有功能。 Here is my little script, which I made thanks to answers from here and here :这是我的小脚本,感谢这里这里的答案:

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

However, when I run it, nothing happens.但是,当我运行它时,没有任何反应。 I've made sure I'm using the correct layer with我已经确定我使用了正确的图层

>>>layer.id()

Since there are no errors, I am assuming my filter expression is not formatted correctly.由于没有错误,我假设我的过滤器表达式格式不正确。 Is that likely the case, or is there a problem with my script logic?可能是这种情况,还是我的脚本逻辑有问题? I'm running Python 3.7.0 on QGIS 3.4.12.我在 QGIS 3.4.12 上运行 Python 3.7.0。

Your filter expression seems working correctly.您的过滤器表达式似乎工作正常。 But calls to deleteFeatures() are only valid for layers in which edits have been enabled by a call to startEditing().但调用 deleteFeatures() 仅对通过调用 startEditing() 启用编辑的图层有效。 Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made.在进行 commitChanges() 调用之前,使用此方法对功能所做的更改不会提交给基础数据提供程序。 Any uncommitted changes can be discarded by calling rollBack().任何未提交的更改都可以通过调用 rollBack() 来丢弃。

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

please refer the documentation Oficial Documentation请参考文档官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM