QWidget delete file on destroy
<p>I'd like to <strong>automatically</strong> delete a temporary file when my QWidget is destroyed (for example, at the end of the program).</p>

<p>I tried to handle it with the <strong>destroyed</strong> signal, but it doesn't work, my callback function is never executed.</p>

<p>Source code:</p>

<pre><code>import sys
from os import remove
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget


class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__(flags=Qt.Window)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        with open('temporary_file.txt', 'w') as f:
            f.write("Hello World!")
        self.destroyed.connect(self._on_destroyed)

    @pyqtSlot(name='_on_destroyed')
    def _on_destroyed(self):
        print("Never executed.")
        remove('temporary_file.txt')

app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
</code></pre>

<p>You should use <a href="http://doc.qt.io/qt-5/qwidget.html#closeEvent" rel="nofollow"><code>closeEvent</code></a> for this:</p>

<pre><code>class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__(flags=Qt.Window)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        with open('temporary_file.txt', 'w') as f:
            f.write("Hello World!")

    def closeEvent(self, event):
        print('close event')
        remove('temporary_file.txt')
</code></pre>

python qt pyqt