If it were a single feature to export you could use an action with canvas scope (i.e., interacting with the canvas), but since you may export several features, an action with layer scope fits better.
Action's code:
from qgis.utils import iface
from qgis.core import QgsProject, QgsVectorFileWriter, QgsCoordinateReferenceSystem
path = "/tmp/gpx/sample.gpx"
layer = QgsProject.instance().mapLayer("[% @layer_id %]")
if layer.selectedFeatureCount():
result, error_string = QgsVectorFileWriter.writeAsVectorFormat(
layer,
path,
"utf-8",
QgsCoordinateReferenceSystem(4326),
"GPX",
onlySelected=True,
datasourceOptions=["GPX_USE_EXTENSIONS=ON"],
layerOptions=["FORCE_GPX_ROUTE=YES"])
if result == QgsVectorFileWriter.NoError:
iface.messageBar().pushSuccess(
"Export2GPX",
"Exported {count} lines to <a href='file://{path}'>{path}</a>".format(
count=layer.selectedFeatureCount(),
path=path))
else:
iface.messageBar().pushWarning("Export2GPX", "Ouch! Errors exporting: {}".format(error_string))
else:
iface.messageBar().pushInfo("Export2GPX", "First select some features...")
Note 1: There is a new method (writeAsVectorFormatV2
) for exporting vector layers in the API. You can find the same action's code using such method in this link.
Note 2: Of course you should tweak the code snippet so that it reflects you intention. For instance, I'm forcing the output to be Routes with parameter FORCE_GPX_ROUTE
. You could also use random file names so that you don't overwrite previous exports.