Monday 28 May 2018

qgis - Open mail client when clicking feature in Attribute Table


One of the attributes/features of my layer contains an email address. I'd like to be able to open the default mail client by clicking on the mail address from the Attribute Table.


After some initial investigation I've found, what seems to be, two different possibilities.


1) I could make an action 'Layer Properties/Actions', or


2) perhaps I could change the fields 'Edit widget' in Layer 'Properties/Fields' to a 'Web view', and that would take care of it(?)



On option 1) I'm a bit unsure how to create an action programmatically using PyQGIS. I've found that a QgsVectorLayer has a function actions() that returns a QgsAttributeAction object. The QgsAttributeAction has an addAction function, so I should be able to use it like this...


layer = iface.activeLayer()
aa = layer.actions()
aa.addAction(...)

but I'm not a 100% on the arguments. From the documentation:


addAction(QgsAction::ActionType type, QString name, QString action, bool capture=false)

Anyone done this before that could give a few hints?



Answer




Here's a slight refinement to dakcarto's approach. Instead of using QgsAction, you can use a QgsMapLayerAction. This has a few advantages:



  • QgsMapLayerActions aren't shown in the layer property's action tab, and can't be modified or removed by users

  • QgsMapLayerActions can be connected directly to an existing python function in your plugin


Here's a example of creating a QgsMapLayerAction:


l = iface.activeLayer()
#attach a QgsMapLayerAction to the active layer:
openMailAction = qgis.gui.QgsMapLayerAction( "Send an email" , iface, l );
#add the action to the QGIS gui, so that it appears as an action for the layer

qgis.gui.QgsMapLayerActionRegistry.instance().addMapLayerAction(openMailAction)
#connect to action trigger
openMailAction.triggeredForFeature.connect(send_email)

def send_email(layer,feature):
#layer is a reference to the layer the actions was triggered on, feature
#is a reference to the feature the action was triggered for
print feature['EMAIL']

Obviously, you'd still need to insert some python code for opening Outlook and creating an email to the send_email function.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...