如何更改QTreeWidget
项目的父项?
答案 0 :(得分:1)
过程是:
indexOfChild()
获取项目的行号。takeChild()
从父项中删除项目。在下面的示例中,属于第一分支的子项的项目被移至第二分支。
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_())