[pyqt] closing qwidget's parent qapplication

I’m scripting Pyqt Qdialog widgets using py charm. The widgets generally prompt user to select a list item then close and return the value. But I have noticed that when testing outside of Maya, the process does not quit - no “process completed with return code(0)” message from Pycharm.

I assume this means that the qapplication instance is still running. So, how do I have my widget close both itself and the parent qapplication? Is there a best practice for this?

Also, the widgets are ultimately run in Maya. Is a qwidget’s close() method sufficient for garbage collection when Maya is the parent qapplication?

.close() will just hide the dialog, unless setAttribute(QtCore.Qt.WA_DeleteOnClose) has been called.

Which could explain why your app isn’t closing in PyCharm.

Thanks, that did the trick.

I also wonder if there is a possibility of wrapping QApplication in a context manager. I have not built my own context managers, so not sure what’s involved.

Something like this should technically work.
Not sure how useful it is overall though.

import sys
from PyQt5 import QtWidgets 


class QApp(QtWidgets.QApplication):

    def __enter__(self):
        return self


    def __exit__(self, exctype, excval, exctb):
        sys.excit(self.exec_())


if __name__ == '__main__':
    
    with QApp(sys.argv) as app:
        w = QtWidgets.QWidget()
        w.resize(250, 150)
        w.move(300, 300)
        w.setWindowTitle('Simple')
        w.show()