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.