源码:
# 参考网址: https://blog.csdn.net/weixin_42286052/article/details/129532631
import os.path
import sys
from PySide6.QtWidgets import QApplication,QMainWindow,QHBoxLayout,QVBoxLayout,QPushButton,QTreeWidget,QTreeWidgetItem,QTreeWidgetItemIterator
from PySide6.QtGui import QStandardItemModel,QStandardItem
from QTreeWidgetUi import Ui_MainWindow
from PySide6.QtCore import Qt,QAbstractItemModel
import configparserclass ParseNone():def __init__(self,fileName):self.config_path = os.path.join(os.path.dirname(__file__), fileName)self.config_ini = configparser.ConfigParser()self.config_ini.read(self.config_path,encoding="utf-8")# parser = ParseNone("config.ini")class TreeWidgetDemo(QMainWindow,Ui_MainWindow):def __init__(self, parent=None):super(TreeWidgetDemo, self).__init__(parent)self.setWindowTitle('TreeWidget 例子')self.setupUi(self)self.Listener()self.config = ParseNone("config.ini")self.tree = self.treeWidgetself.tree.setHeaderLabels(['中国省份城市'])# 设置列数self.tree.setColumnCount(1)self.tree.setColumnWidth(0, 100)self.preview = QTreeWidgetItem(self.tree) # 实例化一个项目。参数:指定父类self.preview.setText(0, '中国')self.preview.setCheckState(0, Qt.Unchecked)for root in self.config.config_ini.sections():items = self.config.config_ini.items(root)parent = QTreeWidgetItem(self.preview)parent.setText(0, root)parent.setCheckState(0, Qt.CheckState.Unchecked)for item in items:node = QTreeWidgetItem(parent)node.setText(0,item[1])node.setCheckState(0,Qt.Unchecked)# 参数1 复选框的位置 列序号# Qt.Unchecked 没选中# Qt.Checked 选中# Qt.PartiallyChecked 部分选中# self.tree.expandAll()# 让所有的项都是以打开状态显示的。注意必须要在所有项都已经实例化好之后再调用该方法,如果一开始就调用则会没有效果self.tree.itemClicked.connect(self.handleChanged)# def handleChanged(self, item, column):# count = item.childCount()# if item.checkState(column) == Qt.CheckState.Checked:# for i in range(count):# if item.child(i).checkState(0) != Qt.CheckState.Checked:# item.child(i).setCheckState(0,Qt.CheckState.Checked)## if item.checkState(column) == Qt.CheckState.Unchecked:# for i in range(count):# if item.child(i).checkState(0) != Qt.CheckState.Unchecked:# item.child(i).setCheckState(0,Qt.CheckState.Unchecked)def updateParentItems(self,item,column):parent = item.parent()if parent == None: returnparent.setCheckState(column, item.checkState(column))count = parent.childCount()for i in range(count):child = parent.child(i)if child.checkState(column) != parent.checkState(column):parent.setCheckState(column, Qt.CheckState.PartiallyChecked)breakself.updateParentItems(parent, column)def updateChildItems(self, item, column):count = item.childCount()for i in range(count):child = item.child(i)child.setCheckState(column,item.checkState(column))if child.childCount() > 0:self.updateChildItems(child, column)def handleChanged(self, item, column):# 注意,一定要先设置子节点,在设置父节点,不然现象比较奇怪self.updateChildItems(item, column)self.updateParentItems(item, column)self.GetSelectedNode(item, column)def GetSelectedNode(self,item, column):iterator = QTreeWidgetItemIterator(item)while iterator.value():item = iterator.value()# print(item.parent())if item.checkState(column) == Qt.CheckState.Checked:print(item.text(column))passiterator +=1def traverse(self):"""遍历节点"""n = self.treeWidget.topLevelItemCount() # 获取根节点数量for i in range(0, n):item = self.treeWidget.topLevelItem(i) # 循环获取根节点text = item.text(0) # 根节点文字信息(默认一列)count = item.childCount() # 获取当前根节点的子节点数量if count != 0:for j in range(0, count):string = item.child(j).text(0) # 子节点的文字信息print(string)def Listener(self):# 按钮的信号槽连接self.pushButton_add.clicked.connect(self.addTreeNodeBtn)self.pushButton_del.clicked.connect(self.delTreeNodeBtn)self.pushButton_modify.clicked.connect(self.updateTreeNodeBtn)def onTreeClicked(self, qmodelindex):item = self.tree.currentItem()print("key=%s ,value=%s" % (item.text(0), item.text(1)))def addTreeNodeBtn(self):item = self.tree.currentItem()print(item.parent(), item.childCount())node = QTreeWidgetItem(item)node.setText(0, 'newNode')node.setText(1, '10')def updateTreeNodeBtn(self):print('--- updateTreeNodeBtn ---')item = self.tree.currentItem()item.setText(0, 'updateNode')item.setText(1, '20')def delTreeNodeBtn(self):print('--- delTreeNodeBtn ---')item = self.tree.currentItem()root = self.tree.invisibleRootItem()for item in self.tree.selectedItems():(item.parent() or root).removeChild(item)if __name__ == '__main__':app = QApplication(sys.argv)tree = TreeWidgetDemo()tree.show()sys.exit(app.exec())
[中国]
node1 = 北京
node2 = 上海
node3 = 重庆
node4 = 天津
node5 = 广东[广东]
node1 = 广州
node2 = 深圳
node3 = 东莞[贵州]
node1 = 贵阳
node2 = 遵义
node3 = 安顺