PDA

View Full Version : Save model to file



matulik
10th May 2010, 13:47
Hello.
I have a problem. I want to save a QStandardItemModel objects into file.
But... how? :)

Have you got any simple idea?

Lykurg
10th May 2010, 14:58
Loop through your data and save it to a file. But how do you have created your model (on what is it based?)?

victor.fernandez
10th May 2010, 17:14
You should walk through the model and save on an item-by-item basis. You may open a file and use QDataStream to save the contents of each item. For example, assuming the model is a table model (for simplicity):



void loadModel(QIODevice *device, QStandardItemModel *model)
{
QDataStream stream(device);
int rowCount, columnCount;
stream >> rowCount;
stream >> columnCount;

for(int row = 0; row < rowCount; row++)
for(int column = 0; column < columnCount; column++) {
QString item;
stream >> item;
model->setItem(row, column, item);
}
}

void saveModel(QIODevice *device, QStandardItemModel *model)
{
QDataStream stream(device);
int rowCount = model->rowCount();
int columnCount = model->columnCount();
stream << rowCount;
stream << columnCount;

for(int row = 0; row < rowCount; row++)
for(int column = 0; column < columnCount; column++) {
stream << model->item(row, column)->text();
}
}

...

QStandardItemModel myModel;
/* populate the model */

QFile file;
if(file.open(QIODevice::WriteOnly))
saveModel(&file, &myModel);

SykeS
11th May 2010, 20:09
I know that there is something like QStandardItem::write, but I have no idea how to use it.

squidge
12th May 2010, 00:02
QStandardItem::write only writes the data and flags of the item to a selected QDataStream, it doesn't deal with any child elements. Victor's solution looks better for that task.