在python中,可以使用QgsVectorLayer.writeLayerXML和QgsVectorLayer.readLayerXML直接修改数据源,如下面示例所示,在运行和重新加载层上修改DOM文档。
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, )
# 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)
该功能已包含在PickLayer插件中,该插件允许对单击的图层和特征执行操作