3

In my QGIS3 plugin I need to close all open PyQt5 dialogs. The structure of my plugin is like the following code. To be clear, when I call runCloseDialogs() I want to close both dialogs opened by run() and run2() if they are open. How can I do this?

def run(self):  
  self.dlg = Dialog()       
  self.dlg.show()

def run2(self):
  self.dlg2 = Dialog2()
  self.dlg2.show()

def runCloseDialogs(self):
  #close all open dialogs here
1
  • Do you want to close all open dialogs in the plugin OR all open dialogs opened in some specific methods (like run and run2)? Is the question about method-based dialogs or dialog-based dialogs? Mar 10, 2020 at 20:36

1 Answer 1

3

CASE 1: If dialogs are created in the main class defined in main module of the plugin,

  • First, find all attributes of main class. (vars(self))
  • Then, check if any is QDialog and is visible. If it is, hide using setVisible(False)
def runCloseDialogs(self):

    items = vars(self)

    for i in items:
        item = items[i]
        if isinstance(item, QDialog) and item.isVisible(): 
            item.setVisible(False)

CASE 2: If the plugin has any widget (GUI) which contians other Qt elements (for example QPushButton) and dialog window is opened by that element, in this case, dialog window is (probably) child of main widget (GUI). In this case, self stands for GUI.

  • First, find all QDialogs instances of the plugin.
  • Then, check if it is visible. If it is, hide using setVisible(False)
def runCloseDialogs(self):

    for dlg in self.findChildren(QDialog):
        if dlg.isVisible(): 
            dlg.setVisible(False)

The script above close all dialogs defined in the plugin's GUI.

CASE 3: If you want to close only self.dlg and self.dlg2, you can use the following lines:

def runCloseDialogs(self):

    if self.dlg.isVisible():
        self.dlg.setVisible(False)

    if self.dlg2.isVisible():
        self.dlg2.setVisible(False)
4
  • Hi thank you very much. I was asking about the first case, but your answers are both usefull.
    – Lorenzo
    Mar 11, 2020 at 16:49
  • It says: 'Plugin' object has no attribute 'findChildren'
    – Lorenzo
    Mar 11, 2020 at 17:16
  • Ok. I thought run method was defined in a GUI class. I've editted the answer. Mar 11, 2020 at 19:41
  • Thank you, your answers are always very complete
    – Lorenzo
    Mar 11, 2020 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.