My final goal is to be able to digitize a point layer (create new point features) and to have as a default for one of the attributes an attribute from another layer that is at the same location.
Up until now I figured how to access the layer/features/geometry/coordinates/attributes from the source layer. Then I thought that I can just use the feature from the function definition to access its coordinates to compare them with the coordinates in my source layer (they should be the same, as I'm clicking on the same points).
@qgsfunction(args=0, group='Custom') def Extract_Attribute(value1, feature, parent):
But, this feature actually refers to any commited feature, at the moment of the creation of the feature, the feature only exist somewhere in the memory, but even in memory I think that the feature is created only after I fill in some attributes and click ok. I think that what I need to access are the coordinates that the mouse clicked (or snapped on) last. From the documentation it is clear that this is what I have to use QgsPointLocator::Match QgsMapMouseEvent::mapPointMatch()
The problem is that I have only seen this function being used when the event is already passed to the function, which is not the case for a custom express function. How can I do it anyway?
This is what I have until now:
""" Define new functions using @qgsfunction. feature and parent must always be the last args. Use args=-1 to pass a list of values as arguments """ from qgis.core import * from qgis.gui import * from PyQt4 import QtGui @qgsfunction(args='auto', group='Custom') def extract_elevation(source_layer_name, feature, parent): source_layer=None for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.name() == source_layer_name: source_layer = lyr break source_features=source_layer.getFeatures() extracted_attribute = None clicked_coordinates = 'something like QgsMapMouseEvent().mapPointMatch()' for source_feature in source_features: source_geometry=source_feature.geometry() #clicked_coordinates = source_geometry.asPoint()#this line simulates a click on the first feature of the source_layer if clicked_coordinates == source_geometry.asPoint(): extracted_attribute = source_feature['some_attribute'] break #QgsMessageLog.logMessage(str(clicked_coordinates)) return extracted_attribute