[GIS] With QGIS Plugins/PluginBuilder, how to prevent 2nd instance of Plugin from starting

pyqgispythonqgisqgis-2qgis-plugins

I am using QGIS 2.6.0, with PluginBuilder 2.0.3 [checking the version, I just noticed that the 2.1.0 update is available]

I am writing a plugin; it installs and runs. While running, I am able to initiate a 2nd instance of MyPlugin by hitting the MyPlugin Icon on the toolbar, or selecting it with the menu item.

I could add code to remove/disable the icon and menu item at the head of the def run(self) function, and restore it before gracefully exiting the plugin. However, if there is a crash, or non-graceful exit, I won't have access to the icon.

Instead, I wonder if I may test for an already existing instance (say, by discovering the named mainDialog on a list, somewhere? Or some other scheme?) and, if the prior instance exists, bring that existing instance's dialog box to the front and then close the second instance.

MyPlugin's dialog is not modal, by choice, so I would like to prevent a user from initiating two instances.

Suggestions ?

Best Answer

loaded plugins and their instance are available in the dict

qgis.utils.plugins

you can manage load and unload with other methods in qgis.utils (do help(qgis.utils) in pythonconsole to show static methods available)

this is only the base to solve you problem, you should manage check if running or not using some method in your plugin, or you can check if the self.dlg is visible or not.

e.g if your plugin is called "myPlugin", get it instance with:

myPlugin = qgis.utils.plugins["myPlugin"]

then check what you want with e.g:

if (myPlugin.dlg):
    myPlugin.dlg.isVisible()

but probably better a more robust check that depends on the architecture of you plugin. The plugins created with plugin builder create self.dlg instance in the __init__, so it's always available

regards,

Related Question