I'm trying to establish a Postgres connection using QgsCredentials as described here:
The only problem is that I cannot establish a working connection unless I "physically" add the layer to the map canvas (which I don't want because I only want a connection to the DB and a reference to the layer which will be edited later on in the code)
When clicking a button the run function reads:
uri = QgsDataSourceURI() connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: # Isn't this enough to establish the connection and get a valid reference to the layer? uri.setConnection("HOST", "PORT", "DB_NAME", user, passwd) uri.setDataSource("SCHEMA", "TABLE_NAME", "the_geom") LYR = QgsVectorLayer(uri.uri(), "LYR", "postgres") # Unless I add the following line, I am not able to use properly the object # (which asks the user the credentials until he/she inserts the right ones and gets # a working connection with a valid reference to the layer) QgsMapLayerRegistry.instance().addMapLayer(LYR)
What am I doing wrong?
Thanks in advance,