mrg95
mrg95

Reputation: 2418

Create QTreeWidget directories based on file paths/names?

In my project, I have a QVector full of QStrings containing file paths/names that don't actually exist on any drive:

QVector<QString> fileNames["level.dat", "data/villages.dat", "players/player1.dat"]//etc

I want to create a tree in my QTreeWidget that resembles a sort of file directory like this:

https://i.sstatic.net/oIzlp.png

How would I go about creating something like this quickly and efficiently?

Thanks for your time :)

Upvotes: 1

Views: 798

Answers (1)

L&#225;szl&#243; Papp
L&#225;szl&#243; Papp

Reputation: 53155

This solution does not avoid duplicate, so if you need that in the future, you could extend this piece of code with adding valiation for that. Anyway, this code produces the exact ame output for me that you have just described to wish to have.

main.cpp

#include <QTreeWidget>
#include <QStringList>
#include <QApplication>

int main(int argc, char **argv)
{
    QApplication application(argc, argv);
    QStringList fileNames{"level.dat", "data/villages.dat", "players/player1.dat"};
    QTreeWidget treeWidget;
    treeWidget.setColumnCount(1);

    for (const auto& filename : fileNames) {
        QTreeWidgetItem *parentTreeItem = new QTreeWidgetItem(&treeWidget);
        parentTreeItem->setText(0, filename.split('/').first());
        QStringList filenameParts = filename.split('/').mid(1);
        for (const auto& filenamePart : filenameParts) {
            QTreeWidgetItem *treeItem = new QTreeWidgetItem();
            treeItem->setText(0, filenamePart);
            parentTreeItem->addChild(treeItem);
            parentTreeItem = treeItem;
        }
    }

    treeWidget.show();
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++14
SOURCES += main.cpp

Build and Run

qmake && make && ./main

On a site node: you ought to use QStringList rather than QVector. In addition, your current initialization attempt surely results in compiler error. That is invalid initialization.

Upvotes: 3

Related Questions