Load QGIS project from geopackage

578 views Asked by At

My attempt is to use the same function behind the above dialog in which QGIS allow to load project form a geopackage by giving the connection, the path. The idea is to be able to check if a geopackage contains project or not. what I did so far is the following

prj = QgsProject.instance()
prj.read('geopackage:/home/me/Downloads/test.gpkg')

but this gave me an error: ogr error no more rows

Thanks

1

There are 1 answers

0
Thomas On

Try this to check if the Geopackage has a project or not:

import sqlite3
import contextlib

geopackage = r"D:\temp\test.gpkg"

with contextlib.closing(sqlite3.connect(geopackage)) as connection:
    
    cursor = connection.cursor()

    cursor.execute("""
        SELECT name 
        FROM sqlite_master 
        WHERE type='table' 
        AND name='qgis_projects';
        """);
    
    row = cursor.fetchone()
    
    print(f"Contains no projects? {not row}")

And to open a project:

PROJECT_NAME = "proj"
iface.addProject(rf"geopackage:D:\temp\test.gpkg?projectName={PROJECT_NAME}")

It took me quite a while to come up with the solution even though it was right in front of me.

Anyways, I'll leave the initial answer below since it may be useful for others or if you want to know more about QGIS Projects and Geopackages...

Have a look at this GitHub project pka/qgpkg.

The QGIS plugin adds a toolbar button for saving the current project in a GeoPackage file and another one for loading a QGIS project from a GeoPackage file.

However, the project seems not to be maintained anymore since 4 years. So it is not used in QGIS 3.24.1 (which I use) since the project code still uses PyQt4.

There is another project kadas-albireo/kadas-gpkg-plugin which seems to do the same and uses PyQt5.

And I assume these are the relevant C++ classes in the QGIS repo:

You may be able to reverse engineer the code and write your own code based on these projects.