generating tree using Qtreewidget
-
i have a text file which contains data as fallows
1st column is message name, 2nd is message id and 3rd is parent id
i want to create a tree using this data i want to make the messages with parent id -1 as roots
and the other messages should become the chld based on their parent id (eg: message1_1 is a child of message1 since its parent id is 1)i am very new to Qt and i really want some solution and guidelines on how to achieve my task (this may be very fundamental since i am new i am finding it difficult please help)
here is the code how i am trying to do it i am abe to create roots not sure how to create child item
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
root = new QTreeWidgetItem(ui->treeWidget);
//ui->treeWidget->addTopLevelItem(root);
subroot = new QTreeWidgetItem();
child = new QTreeWidgetItem();//opening file to read QFile file("/home/textfiles/data.txt"); if (!file.open(QIODevice::ReadOnly)) { qDebug() << "file not opened"; } QTextStream stream(&file); QString line; while (stream.readLineInto(&line)) { QStringList list = line.split(QLatin1Char('\t'), QString::SkipEmptyParts); qDebug()<<list; if (list.at(2) == "-1") { root = new QTreeWidgetItem(ui->treeWidget); root->setText(0,list.at(0)); } else { } } file.close();
}
if this is not the right way i am open for suggestion
thanks in advance. -
@kook You just have to map the items:
#include <QApplication> #include <QFile> #include <QTreeWidget> #include <QDebug> bool buildTree(const QString & filename, QTreeWidget *treeWidget){ QFile file(filename); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ qWarning() << file.error() << file.errorString(); return false; } QMap<int, QTreeWidgetItem*> items; QTextStream stream(&file); QString line; while (stream.readLineInto(&line)){ QStringList words = line.split(QLatin1Char('\t'), Qt::SkipEmptyParts); if(words.length() != 3){ qWarning() << "content" << words << ", lenght:" << words.length(); continue; } QTreeWidgetItem *item = nullptr; QString text = words.at(0); bool ok; int id = words.at(1).toInt(&ok); if(!ok){ qDebug() << "id not is number"; continue; } int parent_id = words.at(2).toInt(&ok); if(!ok){ qWarning() << "parentId not is number"; } if(parent_id == -1){ item = new QTreeWidgetItem(treeWidget); } else if(items.contains(parent_id)){ item = new QTreeWidgetItem(items[parent_id]); } else{ qWarning() << "parentId: " << parent_id << "not found"; continue; } if(item){ item->setText(0, text); items[id] = item; } } return true; } int main(int argc, char *argv[]) { QApplication a(argc, argv); QTreeWidget w; buildTree("/home/textfiles/data.txt", &w); w.expandAll(); w.show(); return a.exec(); }