Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all layers on Geopackage using pyqgis?

Tags:

gis

qgis

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

like image 426
Felipe Sodre Barros Avatar asked Oct 29 '25 16:10

Felipe Sodre Barros


2 Answers

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)
like image 185
Felipe Sodre Barros Avatar answered Oct 31 '25 11:10

Felipe Sodre Barros


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

like image 27
phborba Avatar answered Oct 31 '25 10:10

phborba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!