PyQt app crashes on exit (Python 3.4.3 / PyQt5 / W

2019-08-12 06:04发布

问题:

I realize this is a bit of a vague question, but I'm not sure how to make it more specific.

The skeleton for my code is below:

from PyQt5.QtCore       import *
from PyQt5.QtGui        import *
from PyQt5.QtWidgets    import *

class FormWidget(QWidget):
    def __init__(self, parent):        
        super(FormWidget, self).__init__(parent)

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        form = FormWidget(self) 
        self.setCentralWidget(form) 

        [do a bunch of stuff with form]


if __name__ == '__main__':

    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

Within the FormWidget class, there is a keyPressEvent() method that traps keyboard input, and on a specific key ('q'), calls this:

mainWindow.close()

Most of the time, that causes the app to exit, as desired. But occasionally (with no predictable pattern that I can discern), it causes a crash (dialog comes up that says 'python.exe has stopped working', with a 'Close program' button).

First question, I guess, is: Is this not the proper way to terminate a PyQt GUI app?

If it is, then second question is: Presumably, my code is misbehaving somewhere. But I'm not sure what sort of misbehavior to be looking for. What sort of mistake could I be making that would cause this?

Any thoughts appreciated.

/John

标签: python pyqt5