2

I have a code to open the layers of a SQLite database. When executing this code, the layers are loaded correctly (1 & 2). However i also need to connect to the database and show the connection in the browser toolbar.

How doe load the connection and let it show in the database browser (3)?

uri = QgsDataSourceUri()
uri.setDatabase(r'C:\\path_to_db\\andorra.sqlite')
schema = ''
tables = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other_relations']
display_names = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other relations']
geom_column = 'geometry'

for i in range(len(tables)):
     uri.setDataSource(schema, tables[i], geom_column)
     iface.addVectorLayer(uri.uri(), display_names[i], 'spatialite')

Screenshot

2

I have found an answer:

con = ['name_of_db','C:\\path_to_db\\andorra.sqlite']
QSettings().setValue("SpatiaLite/connections/%s/sqlitepath" %(con[0]), con[1])
iface.reloadConnections()

This code will create an 'visible' connection with the given sqlite database.

Complete code:

    conn = sqlite3.connect(r'C:\\path_to_db\\andorra.sqlite')
    uri = QgsDataSourceUri()
    uri.setDatabase(r'C:\\\\path_to_db\\andorra.sqlite')
    schema = ''
    tables = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other_relations']
    display_names = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other relations']
    geom_column = 'geometry'

    for i in range(len(tables)):
        uri.setDataSource(schema, tables[i], geom_column)
        iface.addVectorLayer(uri.uri(), display_names[i], 'spatialite')

    db = ['andorra','\\path_to_db\\andorra.sqlite']
    QSettings().setValue("SpatiaLite/connections/%s/sqlitepath" %(db[0]), db[1])
    iface.reloadConnections()

    set_crs = QgsCoordinateReferenceSystem(3857)
    QgsProject.instance().setCrs(set_crs)  #setting the osm CRS

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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