如何在 QTreeView 文件夹旁边显示 children 的数量?
how to show the number of children next to the QTreeView folder?
我正在构建一个基于QFileSystemModel的文件管理系统,需要在文件夹旁边显示子文件夹的数量。
首先,我需要得到children的数量。
我知道 rowCount() 不会起作用。因为只有在展开文件夹时才会计算。
其次,我需要在文件夹名称后面加上数字。
我知道我应该向 QFileSystemModel 添加一个自定义列,但我不知道该怎么做。
所以要获取行数必须在调用fetchMore方法之后完成。以上所有内容都必须在委托中实现。
import sys
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import (
QApplication,
QFileSystemModel,
QStyledItemDelegate,
QTreeView,
)
class StyledItemDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if index.column() != 0:
return
model = index.model()
if model.hasChildren(index):
if model.canFetchMore(index):
model.fetchMore(index)
option.text += " ({})".format(model.rowCount(index))
if __name__ == "__main__":
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
view = QTreeView()
view.resize(640, 480)
view.show()
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
view.setModel(model)
view.setRootIndex(model.index(QDir.currentPath()))
delegate = StyledItemDelegate(view)
view.setItemDelegate(delegate)
sys.exit(app.exec_())
我正在构建一个基于QFileSystemModel的文件管理系统,需要在文件夹旁边显示子文件夹的数量。
首先,我需要得到children的数量。
我知道 rowCount() 不会起作用。因为只有在展开文件夹时才会计算。
其次,我需要在文件夹名称后面加上数字。
我知道我应该向 QFileSystemModel 添加一个自定义列,但我不知道该怎么做。
所以要获取行数必须在调用fetchMore方法之后完成。以上所有内容都必须在委托中实现。
import sys
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import (
QApplication,
QFileSystemModel,
QStyledItemDelegate,
QTreeView,
)
class StyledItemDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if index.column() != 0:
return
model = index.model()
if model.hasChildren(index):
if model.canFetchMore(index):
model.fetchMore(index)
option.text += " ({})".format(model.rowCount(index))
if __name__ == "__main__":
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
view = QTreeView()
view.resize(640, 480)
view.show()
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
view.setModel(model)
view.setRootIndex(model.index(QDir.currentPath()))
delegate = StyledItemDelegate(view)
view.setItemDelegate(delegate)
sys.exit(app.exec_())