views:

173

answers:

1

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"
+1  A: 

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.

gruszczy
Thanks for the response! That's pretty much what I ended up doing. In the actual application I have a widget which gets information from a database, but I pass a database connection to that widget. I was originally trying to open the connection in the __init__ and close the dialog on fail, hence the above example. Instead I'm now opening the connection outside, and if it works I'm passing in a connection reference else I don't run the 'exec_'
Jonathan
I am glad, I could help :-) Happy hacking with pyqt :-)
gruszczy