pyqt Qtreeview分层控件

pyqt Qtreeview分层控件

  • 介绍
  • 效果
  • 代码

介绍

QTreeView 是 PyQt中的一个控件,它用于展示分层数据,如目录结构、文件系统 等。QTreeView 通常与模型(如 QStandardItemModel、QFileSystemModel 或自定义模型)一起使用,以管理数据和提供视图如何显示数据的规则。

效果

代码

python 复制代码
from PyQt5.QtWidgets import QApplication, QTreeView, QVBoxLayout, QWidget
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import Qt


class TreeViewExample(QWidget):
    def __init__(self):
        super().__init__()

        # 初始化布局和视图
        self.initUI()

    def initUI(self):
        # 创建一个垂直布局
        layout = QVBoxLayout()

        # 创建一个模型
        model = QStandardItemModel()

        # 创建根节点
        root_item = model.invisibleRootItem()

        # 添加一些子节点到根节点
        item1 = QStandardItem('Item 1')
        item11 = QStandardItem('Item 1.1')
        item12 = QStandardItem('Item 1.2')
        item1.appendRow([item11, item12])
        root_item.appendRow(item1)

        item2 = QStandardItem('Item 2')
        item21 = QStandardItem('Item 2.1')
        item2.appendRow(item21)
        root_item.appendRow(item2)

        # 创建一个视图并设置模型
        tree_view = QTreeView()
        tree_view.setModel(model)

        # 设置视图的扩展标志以允许所有列展开
        tree_view.setExpandsOnDoubleClick(False)
        tree_view.setRootIsDecorated(False)
        tree_view.setSortingEnabled(True)

        # 添加视图到布局
        layout.addWidget(tree_view)

        # 设置窗口布局
        self.setLayout(layout)

        # 设置窗口标题和大小
        self.setWindowTitle('QTreeView Example')
        self.setGeometry(300, 300, 300, 200)


if __name__ == '__main__':
    app = QApplication([])
    ex = TreeViewExample()
    ex.show()
    app.exec_()
相关推荐
aqi003 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn4 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵20 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent