PyQt self.close() in __init__()

江枫思渺然 提交于 2019-12-01 14:03:09

问题


I encountered a few minor issues while working with PyQt4 under Python 2.7

I'm writing a little project where there are some QDialogs opening each other. So there is one Dialog I open and instantly open another Dialog to check something and when there is an error checking, i want the whole dialog to close. it looks like this:

class MyDialog(QtGui.QDialog):
    def __init__(self):
        ## should get me a 10 digit number input
        text, ok = QtGui.QInputDialog.getText(self, u'Enter check')
    if ok:
        ## if clicked ok, assign tID
        tID = text
    else:
        ## else close
        self.close()

    try:   
        ## checker is a plausibilty check for the input
        ## checks, if tID is a number and 10 digits long
        ## and throws an IntegrityWarning if one of these conditions
        ## is not met         
        tID = self.checker.checkID(tID)
    except IntegrityWarning as e:
        ## on exception show error dialog
        errDialog = QtGui.QMessageBox()
        errDialog.setWindowTitle(u'Fehler')
        errDialog.setText(e.getWarning())
        ok = errDialog.exec_()
        if ok != True:
            ## close the whole dialog if user cancels
            self.close()

    self.tAccount = self.tControl.getAccount(tID)

So this is basically what I do and it works just fine except that I get the Errormessage of using tID before assignment. My Programm works just fine after that but I wonder where the error comes from. What strikes me as curious though, is the fact that even if i put the last assignment of tAccount into a try-except: pass statement, the error is thrown to the console, and not passed, as it should be obviously. So my guess was that i can't simply terminate the programm in the __init__() routine. I tried a return statement instead of the close() statement and destroyed the QDialog in the caller function which is in the MainWindow. This made the Dialog appear and stay empty, as it as modal, i had to close it to resume in the MainWindow.

Can someone please tell me why the Dialog __init__() resumes after being closed?


回答1:


This is normal behavior of Python. self.close() is not a return statement, so it will not exit from __init__.

Furthermore, __init__ does not actually show the dialog on screen, so writing self.close() in __init__ is pointless. I'd suggest restructuring your code so this application logic is outside of the __init__ and will decide whether to initialize and show a MyDialog based on the results from QInputDialog and checker



来源:https://stackoverflow.com/questions/31351116/pyqt-self-close-in-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!