当我的QWidget被销毁时(例如,在程序结束时)我想自动删除临时文件。
我试图用销毁的信号来处理它,但它不起作用,我的回调函数永远不会被执行。
源代码:
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_())
答案 0 :(得分:0)
您应该使用closeEvent
:
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')
答案 1 :(得分:0)
解决方案很简单:将_on_destroyed
替换为__del__(self)
,然后删除插槽注释。这真的就在那里。
QTemporaryFile
成员,它将在销毁时自动删除。