PyQt5基礎學習-QTreeWidget().selectedItem().parent().removeChild(刪除當前所選的節點)


主要介紹節點的刪除, 節點的添加, 節點的修改

ModifyTree.py 

"""
添加, 修改和刪除樹控件中的節點
"""

import sys
from PyQt5.QtWidgets import *

class ModifyTree(QWidget):
    def __init__(self):
        super(ModifyTree, self).__init__()
        self.setWindowTitle("TreeWidget 例子")

        operatorLayout = QHBoxLayout()
        addBtn = QPushButton("添加節點")
        updateBtn = QPushButton("修改節點")
        deleteBtn = QPushButton("刪除節點")
        operatorLayout.addWidget(addBtn)
        operatorLayout.addWidget(updateBtn)
        operatorLayout.addWidget(deleteBtn)

        addBtn.clicked.connect(self.addNode)
        updateBtn.clicked.connect(self.updateNode)
        deleteBtn.clicked.connect(self.deleteNode)

        self.tree = QTreeWidget()

        self.tree.setColumnCount(2)

        self.tree.setHeaderLabels(["Key", "Value"])

        root = QTreeWidgetItem(self.tree)
        root.setText(0, 'root')
        root.setText(1, '0')

        child1 = QTreeWidgetItem(root)
        child1.setText(0, 'child1')
        child1.setText(1, '1')

        child2 = QTreeWidgetItem(root)
        child2.setText(0, 'child2')
        child2.setText(1, '2')

        child3 = QTreeWidgetItem(child2)
        child3.setText(0, 'child3')
        child3.setText(1, '3')

        self.tree.clicked.connect(self.onTreeClicked)

        mainLayout = QVBoxLayout(self)
        mainLayout.addLayout(operatorLayout)
        mainLayout.addWidget(self.tree)

        self.setLayout(mainLayout)
    def onTreeClicked(self, index):
        item = self.tree.currentItem()
        print(index.row())
        print("key=%s, value=%s"%(item.text(0), item.text(1)))

    #添加節點
    def addNode(self):
        print("添加節點")
        #獲得當前的節點
        item = self.tree.currentItem()
        print(item)
        #在當前節點上新建節點
        node = QTreeWidgetItem(item)
        node.setText(0, "新節點")
        node.setText(1, "新值")

    def updateNode(self):
        print("修改節點")
        #獲得當前的節點
        item = self.tree.currentItem()
        #進行節點的修改
        item.setText(0, "修改節點")
        item.setText(1, "值已經被修改")

    def deleteNode(self):
        print("刪除節點")
        #獲得根節點的父節點
        root = self.tree.invisibleRootItem()
        #獲得所選的節點
        for item in self.tree.selectedItems():
            #獲得其父節點然后再刪除其子節點
            (item.parent() or root).removeChild(item)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ModifyTree()
    main.show()

    sys.exit(app.exec_())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM