[GIS] Qgis action adding layers using relative paths

actionsfile pathpythonqgis

in QGIS 2 windows
I have some index layers I use for loading raster and vector tiles through an Python action. Currently I am using absolute paths which works fine but I would like to set it up so other teams can use the tiles. I have been trying to get the path of the active layer (the index layer) and use that but had no luck.

I would also like to be able to load the new layers in a specific group to keep projects tidy – can this be done?

Best Answer

If you want path to the current project you can do:

QgsProject.instance().fileName()

and the layer path using:

iface.activeLayer().source()

Getting the last folder:

>>> p = iface.activeLayer().source()
u'F:\\gis_data\\cadastre.shp'
>>> p = os.path.dirname(p)
u'F:/gis_data'
>>>folder = os.path.split(p)[-1]
u'gis_data'

Then you should use os.path.join to join on your new paths:

>>> newpath = os.path.join(folder, "myfolder", "myfile.shp")
u'gis_data\\myfolder\\myfile.shp'

To load a layer with the new path you would do something like this:

from qgis.utils import iface
p = os.path.dirname(iface.activeLayer().source())
folder = os.path.split(p)[-1]
newpath = os.path.join(folder, "myfolder", "myfile.shp")
iface.addVectorLayer(newpath, 'mylayer', 'ogr')

Just copy and paste this into a layer action and change the type to Python and it should work.

Related Question