4

I have problems with the vector layer rollback and commitChanges function, it doesn't matter wich one i call the vector layer is is Changed.Here is my code i hope someone can help me. This is my firt post and im new with qgis.

from qgis.core import QgsApplication,QgsVectorLayer,QgsVectorDataProvider from PyQt4.QtCore import QVariant

if name == "main":

QgsApplication.setPrefixPath('/usr', True)
QgsApplication.initQgis() 

vLayer = QgsVectorLayer(
            "/home/diademuertos/scripts/qgis/data/point.shp",
            "vLayerTest",
            "ogr")

vLayer.startEditing()

caps = vLayer.dataProvider().capabilities()

if caps & QgsVectorDataProvider.ChangeAttributeValues:
    attrs = { 0: QVariant(2),1: QVariant("B"),2:QVariant("Dont!!!")}
    vLayer.dataProvider().changeAttributeValues({ 1 : attrs })
else:
    print "OOPS"

r = False
if r:
    print "commitChanges"
    vLayer.commitChanges()
else:
    print "rollback"
    vLayer.rollBack()

QgsApplication.exitQgis()

1 Answer 1

7

If you write directly to the dataprovider, there is no edit session management done by QGIS. Instead you should use the editing API by QgsVectorLayer, which will give you the expected results.

QGIS 2.0 (and 1.9 / master)

fid = 1 # feature id
attrs = { 0: 2,1: "B",2:"Dont!!!"} # attributes
vLayer.changeAttributeValues({ fid : attrs })

or a very intuitive method, if you already have a copy of the feature you are going to update

fid = 1 # feature id
feat = vLayer.getFeatures( QgsFeatureRequest().setFilterFid( fid ) ).next()
feat['number']  = 2
feat['char']    = 'B'
feat['advice']  = 'Dont!!!'
vLayer.updateFeature( feat )

QGIS 1.8

fid = 1 # feature id
attrs = { 0: QVariant(2),1: QVariant("B"),2:QVariant("Dont!!!")} # attributes
for attr, val in attrs.iteritems():
    vLayer.changeAttributeValue( fid, attr, val )

There is no need to start an edit session if you use the vLayer.dataProvider().insertEditCommandHere() methods, as the edit command will be executed immediately.

(This is a very common misconception and I guess it should be added to the QGIS documentation and pyqgis cookbook more prominently)

2
  • the function changeAttributeValues do not exists in the QgsVectorLayer, i can call it only through dataProvider. Commented Aug 9, 2013 at 15:03
  • For QGIS 1.8 it would be changeAttributeValue( 1, 0, 2 ) Commented Aug 12, 2013 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.