QGIS – How to Import GPX as Vector Layer Using PYQGIS

gpxpyqgispythonqgisvector

I'm trying to use the python console to import some gpx files as vector layers.
When I do it manually I have to choose which layers to add, my options are:

Select vector layers to add image

I've tried various versions of the code from the manual:

uri = "path/to/gpx/file.gpx?type=track"
vlayer = QgsVectorLayer(uri, "layer name you like", "gpx")

I also tried adding the layer name I want like:

path/to/gpx/file.gpx|layername=track_points?type=track", "layer name you like", "gpx")

Edit:
On each try I don't get any errors, it just doesn't import anything, ie no new layers in the layers panel. I would like to import the files using python as I have quite a large number of them. I could do it manually but I would have to choose the track_points layer for each file

Edit:
From Joseph's answer I adapted his code and got what I wanted, not entirely sure how but if it helps anyone else:

import os
path = 'Path/To/GPX Files/'
names = ["track_points"]
for dirpath, subdirs, files in os.walk(path):
    for f in files:
    layername = f[:-4]
        for name in names: 
            iface.addVectorLayer(os.path.join(dirpath, f)+"?type="+name, layername, "gpx")

Best Answer

This is only half an answer as the following code can be used to import waypoints, routes and tracks but not route_points or track_points (these seem to be replaced by the tracks layer).

import os

path = "path/to/gpx/folder"
names = ["waypoint", "route", "track", "route_point", "track_point"]

for dirpath, subdirs, files in os.walk(path):
    for f in files:
        for name in names:
            iface.addVectorLayer(os.path.join(dirpath, f)+"?type="+name, name, "gpx")

Not sure how to import the last two layers using PyQGIS. The code was adapted from this useful post:

Related Question