In QGIS I've got a Spatialite database containing tables without a geometry column. With the QGIS GUI it is perfectly possible to add such a table as a 'Spatialite vector layer'. But how to do this in Python?
On the console I've tried:
>>> uri = QgsDataSourceURI()
>>> uri.setDatabase('/<path>/test.sqlite')
>>> uri.setDataSource('', 'TestTableName','','','id')
>>> vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', 'spatialite')
>>> QgsMapLayerRegistry.instance().addMapLayer(vlayer)
No result
>>> vlayer.isValid()
False
What is going wrong?
Some extra analysis: When I add this layer by the GUI the uri-description is as follows:
>>> qgis.utils.iface.activeLayer().dataProvider().dataSourceUri()
PyQt4.QtCore.QString(u'dbname=\'/<path>/test.sqlite\' table="TestTableName" sql=')
When I add this layer by the Python console as described above, the uri-description is somewhat different:
>>> uri.uri()
PyQt4.QtCore.QString(u'dbname=\'/<path>/test.sqlite\' table="TestTableName" () sql=')
Could the empty parentheses cause the different behaviour? So maybe QGIS 1.8.0 handles empty parentheses different as no parentheses?
>>> uri.setDataSource('',<table_name>,'')
As adding this layer with the GUI works fine, maybe QGIS is using different code for non geometry tables?