Sunday, 10 July 2016

Check if layer is a QGSVectorLayer from Python Plugin within QGIS


I am trying to extend some concepts in the QGIS Workshop tutorial. Basically, I would like to check if the layer is of type "QGSVectorLayer". In the QGIS Python console, I am able to type


canvas = qgis.utils.iface.mapCanvas()
cLayer = canvas.currentLayer()
type(cLayer).__name__

with no problem. However, when attempting the same from the plugin, I get the following error message:



if type(self.cLayer).name == "QgsVectorLayer": NameError: global name 'cLayer' is not defined




The code is as follows:


def handleLayerChange(self, layer):
self.cLayer = self.canvas.currentLayer()
if self.cLayer:
if type(self.cLayer).__name__ == "QgsVectorLayer":
self.provider = self.cLayer.dataProvider()

Answer



You don't need to compare it using strings or the name of the type. You should just do:


 layer.type() == QgsMapLayer.VectorLayer

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...