get_scripted
get_scripted

Reputation: 7

How to change the parent of QTreeWidget item

How do I change the parent of a of QTreeWidget item?

Upvotes: 0

Views: 1927

Answers (1)

eyllanesc
eyllanesc

Reputation: 244291

The process is:

  • Get the row number of the item using indexOfChild().
  • Remove the item from the parent using takeChild() by passing the index.
  • Add the item to the new parent.

In the following example, items that are children of the first branch are moved to the second branch.

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    button = QtWidgets.QPushButton("Press me")
    tree_widget = QtWidgets.QTreeWidget()
    for i in range(2):
        it = QtWidgets.QTreeWidgetItem(tree_widget.invisibleRootItem(),["{}".format(i)])
        for j in range(4):
            child_item = QtWidgets.QTreeWidgetItem(it, ["{}-{}".format(i, j)])
    tree_widget.expandAll()
    lay = QtWidgets.QVBoxLayout(w)
    lay.addWidget(button)
    lay.addWidget(tree_widget)

    def change_parent(item, new_parent):
        old_parent = item.parent()
        ix = old_parent.indexOfChild(item)
        item_without_parent = old_parent.takeChild(ix)
        new_parent.addChild(item_without_parent)

    @QtCore.pyqtSlot()
    def on_clicked():
        it = tree_widget.topLevelItem(0)
        if it.childCount() > 0:
            child_item = it.child(0)
            new_parent = tree_widget.topLevelItem(1)
            change_parent(child_item, new_parent)

    button.clicked.connect(on_clicked)
    w.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions