Changing Qgis layer datasource with python

From release 2.10 QGis Api include QgsVectorLayer::setDataSource method that makes obsolete the instructions cointained in the post for vector layers. For raster layers the method is still valid.

Qgis miss a Arcgis feature of which there is sometimes the need. The vector layer datasource can be changed to point another table keeping related settings and options (graphic styles, labels, join and related relation).

In Qgis there is a workaround method to set datasource editing the content of the qgis project (an XML file) file to modify layers datasource tag: http://gis.stackexchange.com/questions/62610/changing-data-source-of-layer-in-qgis and reloading project.

But in python it is possible to directly modify datasource using QgsVectorLayer.writeLayerXML and QgsVectorLayer.readLayerXML modifying the DOM document on the fly and reloading layer as from example below.

from PyQt4.QtXml import *
from qgis.core import *
from PyQt4.QtXml import *

layer = self.iface.legendInterface().currentLayer()
newDatasource = "NEW DATASOURCE STRING" # get datasource from layer properties general tab
newDatasourceProvider = "ogr" # possible values: ("ogr", "memory", "postgres", "spatialite")

# read layer DOM definition
XMLDocument = QDomDocument("style")
XMLMapLayers = QDomElement()
XMLMapLayers = XMLDocument.createElement("maplayers")
XMLMapLayer = QDomElement()
XMLMapLayer = XMLDocument.createElement("maplayer")
layer.writeLayerXML(XMLMapLayer,XMLDocument)

# modify DOM element with new layer reference
XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(newDatasource)
XMLMapLayer.firstChildElement("provider").firstChild().setNodeValue(newDatasourceProvider)
XMLMapLayers.appendChild(XMLMapLayer)
XMLDocument.appendChild(XMLMapLayers)

# reload layer definition
self.layer.readLayerXML(XMLMapLayer)
self.layer.reload()

# apply to canvas and legend
self.iface.actionDraw().trigger()
self.iface.legendInterface().refreshLayerSymbology(self.layer)

The feature has been included in PickLayer plugin that allows to perform actions on clicked layer and feature

contextmenu

changedatasource

Download Plugin

Advertisements

3 comments

  1. Pingback: Changing Qgis layer datasource with python | Geo-How-To News
  2. Pingback: Changing datasource with Layer Board plugin | GEOGEARS
  3. Pingback: changeDataSource plugin release 1.0 | GEOGEARS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s