3

I have a vector file that contains multiple layers, if I open it in QGIS I get the "Select vector layers to add dialog" and I can choose one and it loads fine.

However in a .py script if I load it via

layer = QgsVectorLayer(filename, "mylayer", "ogr")

I just get one of the layers (layer 0)

How do I specify which layer I want to load? Or if it IS actually loading all of them, how do I change to the one I want?

My full script

import os
import sys
import qgis
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ogr

qgs = QgsApplication([], False)
QgsApplication.setPrefixPath( r"C:\Program Files\QGIS 2.18\apps\qgis-ltr", True )
QgsApplication.initQgis()


filename = "C:/datafiles/sourcefile"
if os.path.exists(filename):
    print('found it')


layer = QgsVectorLayer(filename, "mylayer", "ogr")
if layer.isValid(): 
    print("Layer was loaded successfully!")
else:  
    print("Layer failed to load!")
    sys.exit()

print (layer.type())
print (layer.name())
print (layer.id()) 

print('finished')
qgs.exitQgis()

2 Answers 2

2

...and then five minutes later I stumble across the answer here iface.addVectorLayer on a gml file causes "Select vector layers to add" dialog (pyqgis)

You add

|layername=NameOfTheLayerYouWantToLoad

to the file path, giving:

filename = "C:/datafiles/sourcefile|layername=NameOfTheLayerYouWantToLoad"
1

Welcome to GIS.SE!

If you know the sublayer name already:

layer_path = '/path/to/base_layer.gpx' # GPX is just an example
sublayer_name = 'tracks'
uri = "{}|layername={}".format(layer_path, sublayer_name)
sublayer = QgsVectorLayer(uri, 'layer name', 'ogr')

If you want to know sublayer names given a layer (I'm not sure if there is a better way, though):

if len(layer.dataProvider().subLayers()) > 1:
    for subLayer in layer.dataProvider().subLayers():
        print(subLayer.split("!!::!!")[1])

Which will print something like:

sublayer_name_0
sublayer_name_1
sublayer_name_2
sublayer_name_3

Extracted from an array like this:

['0!!::!!sublayer_name_0!!::!!2!!::!!MultiLineString!!::!!geom', 
 '1!!::!!sublayer_name_1!!::!!4!!::!!MultiPolygon!!::!!geom', 
 '2!!::!!sublayer_name_2!!::!!4!!::!!LineString!!::!!geom', 
 '3!!::!!sublayer_name_3!!::!!12!!::!!LineString!!::!!geom']

Your Answer

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

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