[GIS] How to create a vector layer in PyQGIS from a table without geom column

pyqgisqgis

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?

Best Answer

Finally, I got it working. My analysis seems right. The parentheses in the uri cause the problem. I've solved it as follows:

>>> uri2 = QgsDataSourceURI(uri.uri().remove(' ()'))
>>> vlayer = QgsVectorLayer(uri2.uri(), 'TestLayer', 'spatialite')
>>> vlayer.isValid()
True

It looks like this problem does not occur in QGIS 1.9 >.

Related Question