Reputation: 2418
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:
How would I go about creating something like this quickly and efficiently?
Thanks for your time :)
Upvotes: 1
Views: 798
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.
#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();
}
TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++14
SOURCES += main.cpp
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