[Qgis-user] QgsVectorDataProvider.deleteAttributes(), PyConsole problem

Martin Dobias wonder.sk at gmail.com
Thu Oct 7 13:43:08 PDT 2010


Hi Chris

On Wed, Sep 29, 2010 at 5:32 PM, Chris Carleton
<w_chris_carleton at hotmail.com> wrote:
>
> import qgis.core
> import qgis.gui
> import PyQt4.QtCore
> import PyQt4.QtGui
> vlayer = qgis.utils.iface.activeLayer()
> provider = vlayer.dataProvider()
> feat = QgsFeature()
> newField = QgsField("azimuth",QVariant.Double)
> provider.addAttributes([newField])
> newFieldIndex = provider.fieldNameIndex(newField.name())
> vlayer.commitChanges()
>
> When I try to use the following code to delete the column, the function
> returns 'false';
>
> provider.deleteAttributes([newFieldIndex])

Not all providers support all editing operations. For example, OGR
library does not support deleting attributes. To check what operations
are working, use provider's capabilities() method:

print "delete supported?", provider.capabilities() &
QgsVectorDataProvider.DeleteAttributes


One more note: in the above code, you use layer's commitChanges()
method. This is not necessary (nor correct) here, here's the deal:
When calling provider's editing methods, the changes are immediately
written to the data store (file / database etc). On the other hand,
editing methods of QgsVectorLayer use a temporary buffer and the
workflow is as follows:
1. call vlayer.startEditing() ... otherwise the layer's editing
functions will fail
2. call layer's editing methods ... all changes are kept in the editing buffer
3. call vlayer.commitChanges() ... to push the pending changes to the provider
Alternatively instead of committing changes, you could do a rollback:
vlayer.rollback() to discard any changes.
Both commitChanges() and rollback() quit the editing mode, so you
would have to call startEditing() again.

Regards
Martin



More information about the Qgis-user mailing list