擅长:python、mysql、java
<p>经过大量的研究(这次花了很长时间,所以我把它添加到这里以供将来参考),我发现这样才能真正清除和删除布局中的小部件:</p>
<pre><code>for i in reversed(range(layout.count())):
layout.itemAt(i).widget().setParent(None)
</code></pre>
<p>文档中关于<strong><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html" rel="noreferrer">QWidget</a></strong>的内容是:</p>
<blockquote>
<p>The new widget is deleted when its parent is deleted.</p>
</blockquote>
<p><strong>重要提示:</strong>您需要向后循环,因为从开始处删除内容会转移项目并更改布局中项目的顺序。</p>
<p>要测试并确认布局为空:</p>
<pre><code>for i in range(layout.count()): print i
</code></pre>
<hr/>
<p>似乎还有别的办法。不要使用setParent函数,而是使用<a href="http://pyqt.sourceforge.net/Docs/PyQt4/qobject.html#deleteLater" rel="noreferrer">deleteLater()</a>函数,如下所示:</p>
<pre><code>for i in reversed(range(layout.count())):
layout.itemAt(i).widget().deleteLater()
</code></pre>
<p>文档说明<strong>QObject.deleteLater(self)</strong></p>
<blockquote>
<p>Schedules this object for deletion.</p>
</blockquote>
<p>但是,如果运行上面指定的测试代码,它将打印一些值。这表示布局仍有项,而不是带有<strong>setParent</strong>的代码。</p>