Is it possible to programmatically (in python) access the attribute info of the last added feature in QGIS 2.0 before edits are saved? I'm failing to find a way to get the ID and subsequently other attributes of my feature of interest (the one most recently added).
idx = layer.fieldNameIndex('myField')
myList = []
lastEdited = ID THAT I'D LIKE TO RETRIEVE
for feature in layer.getFeatures():
if feature.id() == lastEdited:
print feature.attributes()[idx]
From this I'd like to get 'myField' of my most recent addition.
UPDATE: Following lead of this thread, I was able to achieve my goals via the Python console, but am failing to get it to work for my plugin.
def updateTableWidget(self, fid):
idx = layer.fieldNameIndex('myField')
myList = []
for feature in layer.getFeatures():
if feature.id() == fid:
myList.append(feature.attributes()[idx])
Via the python console, I was able to connect to my layer like so:
layer.featureAdded.connect(updateTableWidget)
After adding a QgsMessageLog to my function, the attributes were correctly identified. I now have a beginner python issue, however. Calling the function in my plugin as shown below gives me TypeError: updateTableWidget() takes exactly 2 arguments (1 given):
self.updateTableWidget()
The function was called from feature form python file.
Answer
To get the last added feature in QGIS I used the event AddedFeat:
self.connect(self.iface,SIGNAL("currentLayerChanged(QgsMapLayer *)") ,self.ChangedTarget) # in setup
self.connect(layer,SIGNAL("featureAdded(int)"),self.AddedFeat) # from the ChangedTarget
def AddedFeat(self,id):
# added feature by id.
feat = QgsFeature()
self.prelayer.featureAtId(id,feat)
This event has to be connected to the active layer so the connect/disconnect occurs in the ChangedTarget(self,layer):
event.
This returns the feature as it is created, it wont have attributes yet but you can extract them based on a button click or other event qgsVectorLayer::committedAttributeValuesChange
looks promising.
No comments:
Post a Comment