1

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?

Blastcore
  • 360
  • 7
  • 19
  • 4
    Do you need a QTreeWidget, or could you also use a QTreeView with a QFileSystemModel? See [link](http://doc.qt.nokia.com/4.7-snapshot/qtreeview.html#details) for an example. – Andreas Fester Aug 23 '12 at 06:11
  • 4
    You need to figure out the parent item when you add sub-subfolders, i.e. don't `addChild()` to your `m_projectItem` but instead to the node which is currently selected in the view. Apart from that QFileSystemModel probably is the better choice indeed. – Tim Meyer Aug 23 '12 at 06:18

1 Answers1

2

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

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • Okay, so i've got it. Thanks! Whatever, there's one issue. Let's say i have 1 folder called "Hello", and inside that folder there's another folder called "Hello", how would i know in which folder do i put it? – Blastcore Aug 24 '12 at 00:26
  • You always need to consider the parent-child relationship. The name of the folder is not sufficient - you create the "Hello" folder and get back the QTreeWidgetItem which you then use as the parent for your second "Hello" folder. – Andreas Fester Aug 24 '12 at 06:29