Skip to content

Instantly share code, notes, and snippets.

@tcrowson
Last active October 17, 2020 18:51
Show Gist options
  • Save tcrowson/8273931 to your computer and use it in GitHub Desktop.
Save tcrowson/8273931 to your computer and use it in GitHub Desktop.
For PyQt/PySide. A simple function for clearing the contents of a QTreeWidget/QTreeView, since these classes lack convenient clear() or clearContents() methods. Takes a QTreeWidget or QTreeView object as an argument.
import PySide
from PySide import QtGui
def clearQTreeWidget(tree):
iterator = QtGui.QTreeWidgetItemIterator(tree, QtGui.QTreeWidgetItemIterator.All)
while iterator.value():
iterator.value().takeChildren()
iterator +=1
i = tree.topLevelItemCount()
while i > -1:
treeWidget.takeTopLevelItem(i)
i -= 1
@B0und
Copy link

B0und commented Oct 17, 2020

For PySide2

from PySide2.QtWidgets import QTreeWidgetItemIterator
def clearQTreeWidget(tree):
    iterator = QTreeWidgetItemIterator(tree, QTreeWidgetItemIterator.All)
    while iterator.value():
        iterator.value().takeChildren()
        iterator += 1
    i = tree.topLevelItemCount()
    while i > -1:
        tree.takeTopLevelItem(i)
        i -= 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment