How to stop a QDialog from executing while still in the __init__ statement (or immediately after)?

StackOverflow https://stackoverflow.com/questions/2405750

  •  18-09-2019
  •  | 
  •  

Question

I am wondering how I can go about stopping a dialog from opening if certain conditions are met in its __init__ statement.

The following code tries to call the 'self.close()' function and it does, but (I'm assuming) since the dialog has not yet started its event loop, that it doesn't trigger the close event? So is there another way to close and/or stop the dialog from opening without triggering an event?

Example code:

from PyQt4 import QtCore, QtGui

class dlg_closeInit(QtGui.QDialog):
    '''
    Close the dialog if a certain condition is met in the __init__ statement
    '''
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.txt_mytext = QtGui.QLineEdit('some text')
        self.btn_accept = QtGui.QPushButton('Accept')

        self.myLayout = QtGui.QVBoxLayout(self)
        self.myLayout.addWidget(self.txt_mytext)
        self.myLayout.addWidget(self.btn_accept)        

        self.setLayout(self.myLayout)
        # Connect the button
        self.connect(self.btn_accept,QtCore.SIGNAL('clicked()'), self.on_accept)
        self.close()

    def on_accept(self):
        # Get the data...
        self.mydata = self.txt_mytext.text()
        self.accept() 

    def get_data(self):
            return self.mydata

    def closeEvent(self, event):
        print 'Closing...'


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    dialog = dlg_closeInit()
    if dialog.exec_():
        print dialog.get_data()
    else:
        print "Failed"
Was it helpful?

Solution

The dialog will be run only if exec_ method is called. You should therefore check conditions in the exec_ method and if they are met, run exec_ from QDialog.

Other method is to raise an exception inside the constructor (though I am not sure, it is a good practice; in other languages you generally shouldn't allow such behaviour inside constructor) and catch it outside. If you catch an exception, simply don't run exec_ method.

Remember, that unless you run exec_, you don't need to close the window. The dialog is constructed, but not shown yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top