I'm trying to check if my widget is alredy open/visible before showing it (or before run this function). I need to check this because in my QGIS plugin it can happen that I call this function many times. I tried isVisible() but this code returns always false. How to do this check?

def run(self):
  self.dlg = Dialog()
  if self.dlg.isVisible():
    print("is visible")
    print("is not visible")

  # Run the dialog event loop
  result = self.dlg.exec_()

  # See if OK was pressed
  if result:
    #Do something
  • You can do this in several ways: Make the dialog modal so everything else is blocked from the QGIS GUI (even your plugin buttons, preventing opening multiple instances of your Dialog), or, even better, move your self.dlg = Dialog() line to the initGui() so you don't create new dialogs every time you call the run() method. – Germán Carrillo Dec 11 '19 at 0:15
  • @Germán Carrillo commented while I was writing my answer. At least we seem to be on the same page :-) – Ben W Dec 11 '19 at 0:24
  • Thank you both! – Lorenzo Dec 12 '19 at 15:12

Note that you are creating a new instance of your dialog class every time the run() method is called. The isVisible() method is always returning false because you are calling it on the new instance of your dialog before you ever call show() on that object.

Why don't you declare self.dlg as an instance variable in the __init__() method.

For example:

class MyPlugin:

    def __init__(self, iface):
        self.iface = iface
        self.dlg = Dialog()

Then in your run() method:

def run(self):
    if not self.dlg.isVisible():

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.