TransWikia.com

Adding layer using QgsMapLayerRegistry within thread PyQGIS Plugin

Geographic Information Systems Asked on August 16, 2021

I am developing Python QGIS plugin, where I am opening two threads in run function with one thread performing calculation while second thread is printing value looping and when first thread is completed i.e. when self.letsGo variable value changes to True, second thread should add the layer to the QGIS. Everything else is working perfectly fine i.e. it is printing the values in the log panel of QGIS, but when self.letsGo is changed to True, second thread detects it but does not add the layer to map. Is there any dependency of QgsMapLayerRegistry from threading and how can I fix it?

def addLayertoMap(self):
    #add an empty layer to map
    vectorLayer = QgsVectorLayer('Polygon?crs=epsg:3857', 'testLayer' , 'memory')

    while (True):
        QgsMessageLog.logMessage("Looping")
        if self.letsGo==True:
            QgsMessageLog.logMessage("Detected")

            # QgsMapLayerRegistry.instance().addMapLayer(vectorLayer)

            QgsMapLayerRegistry.instance().addMapLayer(vectorLayer)

            QgsMessageLog.logMessage(str(lyr2.name()))
            for lyr in self.iface.mapCanvas().layers():
                QgsMessageLog.logMessage(lyr.name())
            QgsMessageLog.logMessage("Removed")

            break;
        time.sleep(0.5);    

def ouput(self):
    time.sleep(2)
    #connect to database and fetch results
    self.letsGo=True;

def run(self):
    t = threading.Thread(target=self.output)
    t2 = threading.Thread(target=self.addLayerToMap)
    t.start()
    t2.start()

UPDATE

I just figured out that QgsMapLayerRegistry is adding layer to Project properties Identify Layer but not adding it to Layers Panel.

One Answer

How can this be implemented in QGIS3 API as the above is for the QGIS2 and QGIS3 API does not have QgsMapLayerRegistry?

Answered by jkariukidev on August 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP