简体   繁体   中英

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

I have a vector layer with an attribute field called "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.

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(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

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

please refer the documentation Oficial Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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