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?

  • Relative to the project or current layer? – Nathan W Oct 23 '13 at 9:47

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


and the layer path using:


Getting the last folder:

>>> p = iface.activeLayer().source()
>>> p = os.path.dirname(p)
>>>folder = os.path.split(p)[-1]

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

>>> newpath = os.path.join(folder, "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.

  • Thats great - now I need to figure out how to trim the filename off , some sort of a Substr operation – Seth Loader Oct 23 '13 at 11:59
  • the os.path.dirname works now I need to figure out how to use the p in the action - which should be easy but still learning python p = qgis.utils.iface.activeLayer().source() p = qgis.utils.os.path.dirname(p) qgis.utils.iface.addRasterLayer(" ADD PATH HERE [% "TIle" %].asc") – Seth Loader Oct 23 '13 at 13:24
  • See the edit I just made – Nathan W Oct 23 '13 at 13:29
  • That looks like it's gettting closer but the layer to load is a raster layer and the tile to load comes from the [% "TIle" %] attribute in the index layer. Thanks for all the help - I think I can crack it when I have a few mins – Seth Loader Oct 23 '13 at 14:10

This works

    from qgis.utils import iface
    p = os.path.dirname(iface.activeLayer().source())
    p = os.path.dirname(p)
    file = "asc/"+"[% "TIle" %]"+".asc"
    newpath = os.path.join(p,file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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