How to delete QTreeWidgetItem

后端 未结 4 2002
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 02:42

Several webpages say that QTreeWidgetItem can be deleted by deleting or QTreeWidget.clearing. But my code sample below doesn\'t seem to do so. Am I doi

4条回答
  •  执笔经年
    2021-02-20 03:22

    As an epilogue to Avaris' excellent answer, let's flog an even more general-purpose approach applicable to all widgets and widget items (rather than merely top-level tree widget items). Is this supposed Shangri-La too good to be true?

    To quoth the Mario: "Waaaa! Let's-a-go!"

    Here We-A-Go

    Specifically, if your project leverages:

    • PySide2, import the shiboken2 module and pass each tree widget item to be deleted to the shiboken2.delete() function ala:

      # Well, isn't that nice. Thanks, Qt Company.
      from PySide2 import shiboken2
      
      # Add this item to this tree.
      tree = QTreeWidget()
      item = TreeWidgetItemChild()
      tree.addTopLevelItem(item)
      
      # Remove this item from this tree. We're done here, folks.
      shiboken2.delete(item)
      
    • PyQt5, import the sip module and pass each tree widget item to be deleted to the sip.delete() function ala:

      # Well, isn't that not-quite-so-nice. You are now required to import any
      # arbitrary PyQt5 submodule *BEFORE* importing "sip". Hidden side effects are
      # shameful, of course, but we don't make the rules. We only enforce them. For
      # detailed discussion, see:
      #
      #     http://pyqt.sourceforge.net/Docs/PyQt5/incompatibilities.html#pyqt-v5-11
      #
      # If your project requires PyQt5 >= 5.11, the following compatibility hack may
      # be safely reduced to the following one-liner:
      #
      #     from PyQt5 import sip
      from PyQt5 import QtCore
      import sip
      
      # Add this item to this tree.
      tree = QTreeWidget()
      item = TreeWidgetItemChild()
      tree.addTopLevelItem(item)
      
      # Remove this item from this tree.
      sip.delete(item)
      

    Nothing Could Possibly Go Wrong

    Yes, this behaves as expected under all platforms and (PyQt5|PySide2) releases. The Python-specific sip.delete() and shiboken2.delete() methods are high-level wrappers around the underlying C++ delete operator – and operate exactly identically. In the case of QTreeWidgetItem instances, this reproduces the C++ behaviour of immediately removing the passed item from its parent tree.

    Yes, it is both glorious and sketchy. Thanks to alexisdm's relevant answer elsewhere for the motivational impetus behind this overwrought answer. Glory be to alexisdm.

提交回复
热议问题