QTreeView多级树
时间: 2023-07-03 17:30:07 浏览: 63
QTreeView是Qt框架中的一个控件,可以用于显示树形结构数据,包括多级树。下面是一个简单的示例,演示如何使用QTreeView显示多级树。
```python
# 导入需要的模块
from PyQt5.QtWidgets import QApplication, QTreeView, QFileSystemModel, QWidget, QVBoxLayout
from PyQt5.QtCore import QModelIndex
# 创建应用程序对象
app = QApplication([])
# 创建一个文件系统模型
model = QFileSystemModel()
model.setRootPath('') # 设置根目录
# 创建一个QTreeView控件
tree_view = QTreeView()
# 设置模型为树形结构
tree_view.setModel(model)
tree_view.setRootIndex(model.index('')) # 设置根节点索引
# 显示多级树
tree_view.expandAll()
# 创建一个窗口并将QTreeView控件添加到其中
window = QWidget()
layout = QVBoxLayout()
layout.addWidget(tree_view)
window.setLayout(layout)
# 显示窗口
window.show()
# 进入Qt事件循环
app.exec_()
```
在上面的示例中,我们使用QFileSystemModel来创建一个多级树,它可以将文件系统中的目录和文件以树形结构展示出来。我们将QFileSystemModel设置为QTreeView的模型,然后将QTreeView添加到窗口中,并展开所有节点,最后进入Qt事件循环。
如果您需要显示自己的多级树,可以使用QStandardItemModel来创建模型,并使用QStandardItem来添加节点。然后将模型设置为QTreeView的模型即可。