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: 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")

# modify DOM element with new layer reference

# reload layer definition

# apply to canvas and legend

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



Download Plugin



  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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s