Save treeview item
-
I'm learning to program with QT.
I would like to save the contents of a trreview in a file.
Use this code:
@
QDataStream out( &file );QTreeWidgetItemIterator it(ui->treeWidget);
while (*it) {(*it)->write(out);
++it;
}file.close();
@
Does anyone have any idea how to insert the contents trreeview saved when the application starts.
I have been programming with visual studio, c # and C + + (Borland C builder)
Thanks.[edit] code tags added, koahnig
-
The stream cannot store the pointers of the parent items (in fact it can, but it doesn't make sense). So, as an outline of what you can do:
- write the number of toplevel items to the stream
- iterate over the toplevel items
** for each item write the item to the stream
** write the number of children of the item to the stream
*** write the child items to the stream (recursively)
-
Sorry for my English. It is not my mother tongue.
Thanks, works perfectly algoritimo!Save:
@void MainWindow::on_actionSaveTree_triggered()
{QString filename = "D:/test"; QFile file( filename ); if ( !file.open(QFile::WriteOnly)) return; QDataStream out( &file ); int count = ui->treeWidget->topLevelItemCount(); out << count; for(int i=0; i<count; i++) { QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i); item->write(out); saveChild(item, &out); } }
void MainWindow::saveChild(QTreeWidgetItem *item, QDataStream *out) {
int count = item->childCount(); (*out) << count; for(int i=0; i<count; i++) { QTreeWidgetItem *child = item->child(i); child->write(*out); saveChild(child, out); }
}
@
Load:@QString filename = "D:/test";
QFile file( filename ); if ( !file.open(QFile::ReadOnly)) return; QDataStream in( &file ); ui->treeWidget->clear(); while(!in.atEnd()) { int count; in >> count; for(int i=0; i<count; i++) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->read(in); ui->treeWidget->insertTopLevelItem(i, item); addChild(item, &in); } } file.close();
}
void MainWindow::addChild(QTreeWidgetItem *item, QDataStream *in) {
int count; (*in) >> count; for(int i=0; i<count; i++) { QTreeWidgetItem *child = new QTreeWidgetItem(); child->read((*in)); item->addChild(child); addChild(child, in); }
}
@
I find QT, after visual studio and others, and I think it's great!
What I want to program Windows and try Linux
Thanks. -
Looks good to me. Just one remark:
The line
@
while(!in.atEnd()) {
@in the read method shouldn't be necessary. Everything should have been read at the time you finish the included for loop. If the stream does have some data left over, you will add some garbage to the tree view.