[GIS] PyQGIS – load PostGIS layer as editable

postgispyqgispythonqgis

I can load a PostGIS layer on QGIS' map canvas but "Toggle Editing" button comes "inactive". How can I load vector layer as editable?

The code given below loads PostGIS layer on map canvas & "Toggle Editing" button comes "active" but once I run the script below in Python console; when I press "Toggle Editing" button, QGIS gives me an info message: "Start editing failed: Provider cannot be opened for editing":

sql = "(SELECT * FROM tablename)"
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "database", "postgres", "password")
uri.setDataSource("", sql, "geom", "", "gid")
vlayer = QgsVectorLayer(uri.uri(), "abc", "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

# should the layer be set as "active" ???

vlayer.dataProvider()
vlayer.dataProvider().capabilities()
vlayer.startEditing()
iface.actionToggleEditing().setEnabled(True)

Can someone please give me a hint on how to load an editable layer programmatically?

Best Answer

To load a shapefile into QGIS and set the layer as "editable", I executed the code below in the Python Concole:

LayerName =iface.addVectorLayer("/Path/To/Your/Shapefile.shp", "name", "ogr")
qgis.utils.iface.setActiveLayer(LayerName)
qgis.utils.iface.actionToggleEditing().trigger()

For PostGIS tables this blog post may help to set up the SELECT statement in order to load the PostGIS table successfully. Once the layer has been loaded into QGIS I assume the code below will enable/disable editing:

qgis.utils.iface.setActiveLayer(LayerName)
qgis.utils.iface.actionToggleEditing().trigger()

I have not tried the PostGIS example yet. This is my first post on GIS StackExchange so I hope it helps.

Related Question