4

I am studying about pyqgis (using the pyqgis cookbook and started loading a vector layer.

So far I was able to open a layer that I already knew exist on a geopackge.

iface.addVectorLayer("./bcim_2016_21_11_2018.gpkg|layername=lim_unidade_federacao_a", "Nome Vetor", "ogr")

Now, I am wondering how could I list all layers hosted on a geopackage, so a can define which layer to load? Thansk in advance

Felipe

2 Answers2

10

I have just found this possibility on PyQGIS CookBook - cheatsheet, which answer my question.

from qgis.core import QgsVectorLayer, QgsProject

fileName = "/path/to/gpkg/file.gpkg"
layer = QgsVectorLayer(fileName,"test","ogr")
subLayers =layer.dataProvider().subLayers()

for subLayer in subLayers:
    name = subLayer.split('!!::!!')[1]
    uri = "%s|layername=%s" % (fileName, name,)
    # Create layer
    sub_vlayer = QgsVectorLayer(uri, name, 'ogr')
    # Add layer to map
    QgsProject.instance().addMapLayer(sub_vlayer)
  • 1
    This code snippet can be slightly modified to read all vectors within an ESRI geodatabase. Just replace `filename` with a path to a gdb file. – Rob Irwin Mar 17 '21 at 15:55
1

Felipe, all layers are stored into gpkg_geometry_columns. So you should query this table using either QSqlDatabase from Qt or sqlite3.

To query the table name, column name and geometry type you can do the following:

select table_name, column_name, geometry_type_name from gpkg_geometry_columns

Hope I could help you!

Philipe

phborba
  • 11
  • 1
  • Great Philipe. Perhaps my question wasn't to clear... Trying to be more objective: what procedure I could run to have a list of tables (I mean layers in the origina question) to know than before loading with `iface.addVectorLayer()`? For instance: in R and using `sf`package, I run `sf_layers("./path_to_gpkg")` to seee all layers hosted in this specific gpkg . Seems that the answer you bring I should know the table name... am I wrong? – Felipe Sodre Barros Jul 13 '19 at 01:01
  • Philip, reading again your answer, I saw I misundertood. Thats what I need. But now my question is: how to pass this query trhu pyqgis? By the way, I wonder if there is a comand *like*: `iface.showAttributeTable(layer)` But to have te available layers... – Felipe Sodre Barros Jul 13 '19 at 01:10
  • I'm afraid pyqgis does not provide what you need. You should query the database and then get the table names that you need. For instance, in the method listClassesFromDatabases from DSGTools you can get the tables you want: https://github.com/dsgoficial/DsgTools/blob/0f2c88cf206b89cb64ada6efff149f4a94c3fb33/core/Factories/DbFactory/geopackageDb.py#L65 – phborba Jul 13 '19 at 01:14