Frage

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?

War es hilfreich?

Lösung

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 :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top