我知道这已经晚了,但我确实找到了解决方案。就我而言,没有内存泄漏,但某些 QObjects 一定没有正确关闭。Python 3,PySide 1.2.1
class CustomWindow(QtGui.QMainWindow):
def cleanUp(self):
# Clean up everything
for i in self.__dict__:
item = self.__dict__[i]
clean(item)
# end cleanUp
# end class CustomWindow
def clean(item):
"""Clean up the memory by closing and deleting the item if possible."""
if isinstance(item, list) or isinstance(item, dict):
for _ in range(len(item)):
clean(list(item).pop())
else:
try:
item.close()
except (RuntimeError, AttributeError): # deleted or no close method
pass
try:
item.deleteLater()
except (RuntimeError, AttributeError): # deleted or no deleteLater method
pass
# end clean
if __name__ == "__main__":
app = Qtgui.QApplication(sys.argv)
window = CustomWindow()
window.show()
app.aboutToQuit.connect(window.cleanUp)
sys.exit(app.exec_())
这将遍历主窗口中的所有内容,如果可能,它将关闭并删除所有找到的项目。它使我的应用程序立即关闭,没有内存泄漏或问题。您可能还必须专门关闭某些项目,并确保尝试删除已删除的项目不会导致错误。
编辑
我最终用一个名为QtGui.qApp.closeAllWindows()
. 不过,后来这个问题又来了。我现在认为这与 C++ 和 python 对象不同步以及如何清理对象有关。
class CloseAllFilter(QtCore.QObject):
"""Event filter for closing all windows if the widget is closed."""
def eventFilter(self, receiver, event):
results = super().eventFilter(receiver, event)
if event.type() == QtCore.QEvent.Close and event.isAccepted():
for win in QtGui.qApp.topLevelWidgets():
if win != receiver:
try:
win.close()
# win.deleteLater() # This seemed to make python crash more consistently.
except (AttributeError, RuntimeError):
pass
return results
# end class CloseAllFilter
window.__close_all_filter = CloseAllFilter()
window.installEventFilter(window.__close_all_filter )
这似乎对我更有效。我还将我的应用程序和窗口包装在一个函数中。