QTreeWidget for File Tree and Sub-folders

倖福魔咒の 提交于 2019-12-24 12:50:07

问题


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.
}

Would i need to create another function (something like addSubFolder) to add folders inside another folders?


回答1:


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;
}

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");
}

Disclaimer: I have not tested the code - I have recently implemented something similar in Python :)



来源:https://stackoverflow.com/questions/12084778/qtreewidget-for-file-tree-and-sub-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!