PDA

View Full Version : Write tree model to file



justin123
16th May 2012, 01:15
I'm trying to come up with a way to write a tree model to a file. My tree model has child items that can have child items and so on. The problem is each parent item doesn't know the depth of its "branch" of the tree which makes iterating through the model difficult. You'd think that you could just check if an item has children and write those, but then you would have to account for child items having child items leaving you with an infinite amount of for statements. Anyways, is there some sort of method for writing these kind of data models to a file using QDataStream?

d_stranz
16th May 2012, 03:44
Can you say "recursion"?


void WriteIndex( const QAbstractItemModel & model, const QModelIndex & index, QTextStream & stream, int level )
{
stream << level << index.row() << index.column() << index.data() << endl( stream );
if ( model.hasChildren( index ) )
{
int nRows = model.rowCount( index );
int nCols = model.columnCount( index );
for ( int nRow = 0; nRow < nRows; ++nRow )
{
for ( int nCol = 0; nCol < nCols; ++nCol )
{
WriteIndex( model, model.index( nRow, nCol, index ), stream, level + 1 );
}
}
}
}

and you start the whole thing off with the model index that is the root of your tree and level = 0.

Since the QModelIndex::data() method returns a QVariant, you'll probably need to call one of the QVariant::to...() methods when writing.

ChrisW67
16th May 2012, 03:59
This is a classic recursive algorithm (http://en.wikipedia.org/wiki/Recursion_%28computer_science%29) application.

Edit: Must remember to preview before submitting... especially when I've been distracted for a while.