QTreeWidget用于文件树和子文件夹 [英] QTreeWidget for File Tree and Sub-folders
问题描述
所以,我正在使用的是一个QTreeWidget来制作一个文件树.我可以轻松地创建文件和文件夹.但是,当我们谈论子文件夹时,问题就来了.例如:
So, what i'm using is a QTreeWidget to make a File-Tree. I can easily create the files, and folders. But the issue comes when we talk about sub-folders. For example:
Folder1
Folder1/SubFolder1
Folder1/SubFolder1/SubFolder2
如何精确创建子文件夹?这是我制作文件夹的代码:
How do i exactly create the sub-folders? Here's my code to make the folders:
void Tree::addFolder(const QString &folderName)
{
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setText(0, folderName); // Sets the text.
m_projectItem->addChild(item); // Adds it to the main path. (It's a QTreeWidgetItem)
this->expandItem(item); // Expands.
}
我是否需要创建另一个函数(例如addSubFolder之类)以在另一个文件夹中添加文件夹?
Would i need to create another function (something like addSubFolder) to add folders inside another folders?
推荐答案
我假设m_projectItem是您的根节点. 我将实现类似于
I am assuming that m_projectItem is your root node. I would implement the addFolder method similar to
QTreeWidgetItem* Tree::addFolder(QTreeWidgetItem* parent, const QString &folderName) {
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setText(0, folderName); // Sets the text.
parent->addChild(item); // Adds it to its parent (It's a QTreeWidgetItem)
this->expandItem(item); // Expands.
return item;
}
然后,我将实现另一种方法,即通过适当地调用addFolder来设置树-参见您的示例,以其最简单的静态形式可以是
Then I would implement another method which is setting up the tree by calling addFolder appropriately - referring to your example, in its simplest static form this could be
void Tree::createTree() {
QWidgetItem* f1 = addFolder(m_projectItem, "Folder1");
QWidgetItem* sf1 = addFolder(f1, "SubFolder1");
addFolder(sf1, "SubFolder2");
}
免责声明:我尚未测试代码-我最近在Python中实现了类似的功能:)
Disclaimer: I have not tested the code - I have recently implemented something similar in Python :)
这篇关于QTreeWidget用于文件树和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!