<p>经过几次尝试,我发现如果在类之外声明<code>doSomeDestruction</code>,它就可以工作
<strike>但我不知道为什么。</strike>如<a href="https://stackoverflow.com/a/7944336/2325172">this</a>答案中所写,这是因为<code>At the point destroyed() is emitted, the widget isn't a QWidget anymore, just a QObject (as destroyed() is emitted from ~QObject)</code>。<br/>
这意味着当您的函数被调用时,如果您在类中编写它,它已经被删除。(也可以查看qt兴趣邮件列表中的<a href="http://comments.gmane.org/gmane.comp.lib.qt.general/21821" rel="nofollow noreferrer">here</a>:<code>Ok , I am sorry for stupid question. The signal is emitted, but the slot is not called for the obvious reason, that is because object is already deleted.
</code>)</p>
<p><strong>编辑:</strong>我找到了两种方法让它真正发挥作用:</p>
<ol>
<li>在<code>ret = app.exec_()</code>之后添加一个简单的<code>del window</code>。</li>
<li><p>在主窗口(不是小部件)中设置<code>WA_DeleteOnClose</code>属性:<br/>
在程序的顶部:</p>
<pre><code>from PyQt4 import QtCore
</code></pre>
<p>已更改的<code>__init__</code>函数:</p>
<pre><code>class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
self.widget = MyWidget(self)
</code></pre></li>
</ol>