I need to create function that assembles QgsFeature from scratch: takes id, dictionary of attributes, and geometry as input. The issue is that feature that is being created doesn't belong to any layer and not going to before heavy processing that needs this feature to have attributes callable by name. Attributes are fixed: 2 fields, one is string and other is real. From documentation I can see that QgsFields() can help me to assign fields to the feature being created. Though I don't get how does QgsFields() work.

#att_dic = {u'value': value, u'zone': str(some_data)}
def makeFeature(fid, att_dic, geom):
    feat = QgsFeature(**some QgsFields(.....) magic??? **, id=fid)
    for name, value in att_dic.iteritems():
        feat.setAttribute(name, value)
    return feat

You just need to define the QgsFields object in this way:

from PyQt4.QtCore import QVariant
fields = QgsFields()
fields.append(QgsField("mystring", QVariant.String))
fields.append(QgsField("myreal", QVariant.Double))

Then you can use it to create your feature:

feat = QgsFeature(fields, fid) # fid should be an integer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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