2

So I'm working on something where i need to use threads from python console of QGIS. The following line of code adds layer successfully

iface.addVectorLayer("D:\ArcGIS Misc\Atlas\points.shp", 'Points', 'ogr')

But when i try to run the following code:

from threading import Thread
class AddLayer(Thread):
    def __init__(self, iface):
        Thread.__init__(self)
        self.iface = iface

    def run(self):
        self.iface.addVectorLayer("D:\ArcGIS Misc\Atlas\points.shp", 'Points', 'ogr')
        print 'added'

AddLayer(iface).start()

then i only get added printed on the console but the layer is never added. When i do it from a class which is not inherited from Thread then it works fine. Help Needed

-1

You must register your layer with Map Layer Registry and then insert it into the Layer Tree (when working from the console, this is done automatically). Try something like:

def run(self):
    self.iface.mapCanvas().freeze() # toggles rendering off to prevent deadlocking the map
    self.mylayer=self.iface.addVectorLayer("D:\ArcGIS Misc\Atlas\points.shp", 'Points', 'ogr')
    self.ProjInstance=QgsProject.instance() # get project instance
    self.root=self.ProjInstance.layerTreeRoot() # get layer tree
    QgsMapLayerRegistry.instance().addMapLayer(self.mylayer) # add layer to the registry
    self.root.addLayer(self.mylayer) # add layer to the layer tree
    self.iface.mapCanvas().freeze(False) # unfreeze renderer
    print 'added'

QgsProject and QgsMapLayerRegistry are in the qgis.core module:

from qgis.core import *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.