[GIS] Changing attribute data types using PyQGIS

fields-attributespyqgispythonqgis-plugins

OK, so I've already asked a question how to access attribute data types when developing plugin for QGIS, using PyQGIS. And one helpful member said i should use pendingFields() method on the current layer. Here is the link on that query: LINK

Indeed I could access them but when I tried to change the data type with setType() and setTypeName() functions, it didn't work. When I queried the objects with type() and typeName() they showed the new data types I have given them, but when I wanted to enter new values for some feature I realized that this layer doesn't recognize new data types.

For example, first attribute field has by default Real data type, so it recognizes only numbers. I converted that field to String using command:

fields[0].setType(10)

btw:

fields = currentLayer.pendingFields()

But the field still acts like before, and doesn't recognize letters, only numbers.
How to change data types? Is it even possible? Or you can only define data type for new attribute?

Best Answer

Changing of attribute types simply isn't supported.

You can only QgsVectorLayer::addAttribute or QgsVectorLayer::deleteAttribute. Those two will only work while editing (ie. between QgsVectorLayer::startEditing() and QgsVectorLayer::commitChanges()) and then QgsVectorLayer::pendingFields() will reflect those changes and so will the UI.

When not editing pendingFields() returns the fields of the vector data provider.

Related Question