I would like to directly export selected tracks of a line layer as gpx. The common way is:

  1. Select the line-layer
  2. select the tracks for export
  3. right-click on the layer -> save selected features as...
  4. choose gpx-format, a filename and EPSG:4326 as CRS
  5. hit OK-Button

But this takes too much time. So I'm looking for a fast solution. I know, the Layer-Actions could be perfect for this task!

How do I export selected features as gpx to a fixed file path with QGIS actions?


1 Answer 1


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.

enter image description here

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(

    if result == QgsVectorFileWriter.NoError:
            "Exported {count} lines to <a href='file://{path}'>{path}</a>".format(
        iface.messageBar().pushWarning("Export2GPX", "Ouch! Errors exporting: {}".format(error_string))
    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.

  • you were some minutes faster than me :-) what do you think about adding some error handling and show messages if the export fails? gist.github.com/thbaumann/…
    – Thomas B
    Jun 22, 2020 at 15:27
  • 1
    I had just added error handling, but showing error message would be handy, right! I'll borrow that from your link, thanks. Jun 22, 2020 at 15:30
  • What I have to do, if I want a single gpx-file for each selected feature named by the filed "name"?
    – MartinMap
    Jun 30, 2020 at 12:39
  • I see 2 options: 1) You could use the "Convert Format" algorithm for vectors, where you can iterate selected features to get independent outputs. I don't know if you can name output laters according to an attribute, for that you should read the OGR docs; and 2) Add more Python logic to the action, first saving selected feature ids, and then iterating through those ids and saving with its proper name. Let me know if you need more help. Jun 30, 2020 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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