Sunday, 18 November 2018

python - Odd behavior in a QGIS plugin: my function is triggered twice


I have a plugin with a function (triggered by a button) that selects a specific layer by name, then shows its attribute table. When I close the plugin and open it again, the attribute table pops up twice, and repeating this keeps adding another table popup. What's wrong?


Code:


def showTable(self):
for lyrs in QgsMapLayerRegistry.instance().mapLayers().values():

if lyrs.name() == "TestFeatures":
lyrTest = lyrs
self.iface.showAttributeTable(lyrTest)

Answer



You are probably setting a connection between a SIGNAL (button clicked) and a SLOT (your method showTable) every time your plugin is open (run() method?) and you are not disconnecting such SIGNAL/SLOT when your plugin is closed. This leads to a new call to showTable() every time you open your plugin, because there's a new connection calling it.


A couple of solutions for this problem are to:



  • Disconnect your SIGNAL/SLOT when closing the plugin; or (recommended)

  • Set your connection only in the initGui() method of your plugin, this way a new connection won't be set when opening your plugin, but only when initializing QGIS (or reloading the whole plugin).



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...