5

I made a little plugin in QGIS, and I got some strange results. The program now mirrors the "Layers Panel". When I add or delete layers from the Panel the QListWidget module get the names of layers. I connected the function to the legendLayersAdded and to layersRemoved SIGNAL.

THE PROBLEM: The add part is ok, and if I remove ONE layer that's fine too. But if I remove multiple layers, the widget gets back the rest of layers' names multiple times (count of removed layers).

Community edit: For however many multiple layers are removed, the remaining layers appear in the list that many times. Ergo, if 3 layers are removed, and there is 1 remaining, that layer appears 3 times in the additional layer pane:

image of the issue

It's like the signal calls the function recursively!? I tried with the layerWasRemoved Signal and the result was the same I made a video of it because it is hard to explain.

[https://www.youtube.com/watch?v=NuLtANtlLtE&feature=youtu.be]

Here is the code:

def ablak(self):
layers = [] 
self.dockwidget.telepules_kezelo.clear()
layers = self.iface.legendInterface().layers()
print "Befor" # Befor layer list
print layers # Layer list "from Layers Panel"
print "After" # After layer list
i = 0 # Just a counter for debubing
lista = self.dockwidget.telepules_kezelo
for layer in layers:
    print layer.name()
    lista.addItem(layer.name())
    i = i+1
    print i # Counter for debuging
layers = []


QgsMapLayerRegistry.instance().legendLayersAdded.connect(self.ablak)

QgsMapLayerRegistry.instance().layersRemoved.connect(self.ablak)

I fade out the problem with transfer the self.dockwidget.telepules_kezelo.clear() line after the Print After line. And it's working fine, but I am really frustrated with it.

  • 1
    One solution could be to update the list from the Table of Contents every time the map updates, the layers change, etc., depending on what you want to do with this module. As far as solving within the parameters given, I'm not really clear on how to fix that personally. – coneypylon Mar 1 '17 at 15:55
4

I think your function can be shortened down a bit as you have defined lists but not really using them (atleast not what you have shown).

The following function does the following whenever a layer(s) are added or removed (as suggested by @coneypylon):

  • Clears the widget
  • Only adds the layers currently loaded in the panel

(Tested on QGIS 2.18.2):

def ablak(self):
    self.dockwidget.telepules_kezelo.clear()
    for layer in QgsMapLayerRegistry.instance().mapLayers().values():            
        self.dockwidget.telepules_kezelo.addItem(layer.name())

QgsMapLayerRegistry.instance().legendLayersAdded.connect(self.ablak)
QgsMapLayerRegistry.instance().layersRemoved.connect(self.ablak)

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.