MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

12.4 PyQt5表格介绍【树控件】-QTreeView

2025-01-12 15:23 huorong 精选文章 3 ℃ 0 评论

1.QTreeView简介

PyQt5中QTreeView用于展示层次结构的数据,比如文件系统目录、关系数据库中的树形结构等。

2.QTreeView案例

from PyQt5.QtWidgets import QApplication, QTreeView, QVBoxLayout, QWidget
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.Qt import QAbstractItemView
import sys


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

        self.setWindowTitle("QTreeView演示")
        self.resize(600, 400)

        # 创建 QTreeView 实例
        self.tree_view = QTreeView()

        # 创建数据模型
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(['名称', '描述'])

        # 设置模型
        self.tree_view.setModel(self.model)

        # 设置根节点
        root_node = self.model.invisibleRootItem()

        # 添加数据
        self.add_items(root_node)

        self.tree_view.clicked.connect(self.clicked)
        self.tree_view.doubleClicked.connect(self.double_clicked)
        self.tree_view.expanded.connect(self.expanded)

        # 布局
        layout = QVBoxLayout(self)
        layout.addWidget(self.tree_view)

    def add_items(self, root_node):
        # 添加第一层节点
        item1 = QStandardItem('Item 1')
        item2 = QStandardItem('Item 2')

        # 为节点添加描述列
        item1_desc = QStandardItem('Item 1 描述')
        item2_desc = QStandardItem('Item 2 描述')

        # 将节点添加到模型中
        root_node.appendRow([item1, item1_desc])
        root_node.appendRow([item2, item2_desc])

        # 添加第二层节点
        item1_child1 = QStandardItem('Item 1 Child 1')
        item1_child2 = QStandardItem('Item 1 Child 2')

        # 展开指定节点
        # self.tree_view.expand(self.model.indexFromItem(item1))

        # 为子节点添加描述列
        item1_child1_desc = QStandardItem('Item 1 Child 1 描述')
        item1_child2_desc = QStandardItem('Item 1 Child 2 描述')

        # 将子节点添加到第一个节点下
        item1.appendRow([item1_child1, item1_child1_desc])
        item1.appendRow([item1_child2, item1_child2_desc])

    def clicked(self, index):
        print(self.tree_view.currentIndex())
        print(self.model.data(index))

    def double_clicked(self, index):
        print(self.model.data(index))

    def expanded(self, index):
        print(self.model.data(index))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

3.运行结果

4.常用方法

方法

描述

setModel(model)

设置模型: QStandardItemModel:通用的模型,适合大多数应用场景 QSqlTableModel:用于管理和显示数据库表的数据,通过PyQt5.QtSql导入 QSqlQueryModel:用于执行和显示 SQL 查询的结果,通过PyQt5.QtSql导入 QFileSystemModel:用于管理和显示文件系统的数据

model()

获取 QTreeView 当前使用的数据模型

expandAll()

展开所有项

collapseAll()

折叠所有项

expand(const QModelIndex &index)

展开指定索引对应的项,通过模型中的indexFromItem方法获取索引

collapse(const QModelIndex &index)

折叠指定索引对应的项,通过模型中的indexFromItem方法获取索引

setRootIndex(const QModelIndex &index)

设置视图的根索引,通过模型中的indexFromItem方法获取索引

rootIndex()

返回当前的根索引

setUniformRowHeights(bool enable)

设置是否使用统一的行高

uniformRowHeights()

返回是否使用统一的行高

setAnimated(bool enable)

设置是否启用动画

isAnimated()

返回是否启用了动画

setSortingEnabled(bool enable)

设置是否启用排序

isSortingEnabled()

返回是否启用了排序

setAllColumnsShowFocus(bool show)

设置当某一行获得焦点时,是否在所有列上都显示焦点矩形(即高亮显示整个行)

allColumnsShowFocus()

返回是否当某一行获得焦点时在所有列上显示焦点举行

setWordWrap(bool enable)

设置是否启用文本换行

wordWrap()

返回是否启用了文本换行

setIndentation(int indent

设置缩进量(单位为像素)

indentation()

返回缩进量

header()

获取QTreeView表头对象,可以对表头进一步详细设置: setStretchLastSection(Bool):设置最后一列是否自动拉伸以填满剩余空间 setVisible(Bool):设置表头是否可见 setDefaultAlignment(Qt.Alignment):设置表头项的默认对齐方式 setSectionsMovable(Bool):设置列是否可拖动重新排序 setHighlightSections(Bool):设置当选中某一列时,表头是否高亮显示该列 setSortIndicatorShown(Bool):设置是否显示排序指示器(一般用于表头) setSortIndicator(logicalIndex: int, order: Qt.SortOrder):设置某列为排序列,并指定升序或降序 resizeSection(logicalIndex: int, size: int):指定列的宽度 hideSection(alogicalIndex: int):隐藏指定行 showSection(alogicalIndex: int):显示指定行

setSelectionMode(mode)

设置选择模式(单选、多选等): QAbstractItemView.NoSelection:不允许选择。 QAbstractItemView.SingleSelection:一次只允许选择一个单元格。 QAbstractItemView.MultiSelection:允许选择多个单元格。 QAbstractItemView.ExtendedSelection:允许使用 Shift 或 Ctrl 键进行扩展选择。 QAbstractItemView.ContiguousSelection:只允许选择连续的项目

selectionModel()

返回视图的选择模型

currentIndex()

返回当前选中的索引

setCurrentIndex(const QModelIndex &index)

设置当前选中的索引

scrollTo(index, hint)

滚动到指定的单元格 常用的滚动行为 (hint): QAbstractItemView.EnsureVisible:确保单元格可见 QAbstractItemView.PositionAtTop:滚动使单元格位于顶部 QAbstractItemView.PositionAtCenter:滚动使单元格位于中心

setRootIsDecorated(bool decorate)

设置是否装饰根索引

rootIsDecorated()

返回根索引是否被装饰

setAlternatingRowColors(bool enable)

设置是否使用交替行颜色

alternatingRowColors()

返回是否使用交替行颜色

setItemsExpandable(bool expandable)

设置项是否可展开

isItemsExpandable()

返回项是否可展开

setExpandsOnDoubleClick(bool expand)

设置是否在双击时展开项

expandsOnDoubleClick()

返回是否在双击时展开项

setEditTriggers(QAbstractItemView.EditTriggers)

QAbstractItemView.NoEditTriggers:禁止编辑 QAbstractItemView.DoubleClicked:双击编辑 QAbstractItemView.SelectedClicked:点击选中项时触发编辑 QAbstractItemView.AnyKeyPressed:按下任何键时触发编辑 QAbstractItemView.AllEditTriggers:启用所有编辑触发条件 组合触发条件时,条件之间用 | 隔开。

editTriggers()

返回编辑触发器。

visualRect(const QModelIndex &index)

返回给定索引在视图中的可视化矩形,通过模型中的indexFromItem方法获取索引

visualRegionForSelection(const QItemSelection &selection)

返回给定选择在视图中的可视化区域,通过selectionModel().selection()获取

isPersistentEditorOpen(const QModelIndex &index)

返回指定索引的编辑器是否持久打开,通过模型中的indexFromItem方法获取索引

closePersistentEditor(const QModelIndex &index)

关闭指定索引的持久编辑器

openPersistentEditor(const QModelIndex &index)

打开指定索引的持久编辑器

selectedIndexes()

返回当前选择的所有索引

setHorizontalHeaderLabels(list)

设置水平标题(列标题)

4.常用信号

方法

描述

activated(const QModelIndex &index)

当激活一个项时发出。通常是在双击一个项或者按 Enter 键时触发

clicked(const QModelIndex &index)

当单击一个项时发出

doubleClicked(const QModelIndex &index)

当双击一个项时发出

entered(const QModelIndex &index)

当鼠标光标进入一个项时发出

expanded(const QModelIndex &index)

当一个项被展开时发出

collapsed(const QModelIndex &index)

当一个项被折叠时发出

pressed(const QModelIndex &index)

当按下鼠标键时发出

viewportEntered()

当鼠标光标进入视口时发出

rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)

当模型即将从父索引删除一行或多行时发出

rowsInserted(const QModelIndex &parent, int start, int end)

当模型插入一行或多行时发出

rowsRemoved(const QModelIndex &parent, int start, int end)

当模型从父索引删除一行或多行时发出

dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)

当模型中的数据发生改变时发出

headerDataChanged(Qt::Orientation orientation, int first, int last)

当模型中的头部数据发生改变时发出

layoutChanged()

当模型的布局发生改变时发出

modelReset()

当模型重置时发出

modelAboutToBeReset()

当模型即将重置时发出

selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)

当选择发生变化时发出

currentChanged(const QModelIndex ¤t, const QModelIndex &previous)

当前索引发生变化时发出

customContextMenuRequested(const QPoint &pos)

当用户右击视图时发出,通常用于显示上下文菜单

Tags:show columns

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言