【Python】QTreeWidget树形结构添加

2023-10-12 02:20

本文主要是介绍【Python】QTreeWidget树形结构添加,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

源码:

# 参考网址: 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 = 安顺

这篇关于【Python】QTreeWidget树形结构添加的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/192569

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以