Read and write to a file from a QTableView

孤街浪徒 提交于 2019-12-03 22:17:20
QFile file("somefile.bin");

if (file.open(QIODevice::WriteOnly)) {
    QDataStream stream(&file);
    stream << *(model->invisibleRootItem());
    file.close();
}

http://qt-project.org/doc/qt-5.0/qtgui/qstandarditemmodel.html#invisibleRootItem


Edit:

Here is correction (I've checked that it works).

void MainWindow::save()
{
    QFile file("somefile.bin");
    if (file.open(QIODevice::WriteOnly)) {
        QDataStream stream(&file);
        qint32 n(model->rowCount()), m(model->columnCount());
        stream << n << m;

        for (int i=0; i<n; ++i)
            for (int j=0; j<m; j++)
                model->item(i,j)->write(stream);
        file.close();
    }
}

void MainWindow::load()
{
    QFile file("somefile.bin");
    if (file.open(QIODevice::ReadOnly)) {
        QDataStream stream(&file);
        qint32 n, m;
        stream >> n >> m;

        model->setRowCount(n);
        model->setColumnCount(m);
        for (int i=0; i<n; ++i)
            for (int j=0; j<m; j++)
                model->item(i,j)->read(stream);
        file.close();
    }
}

You can browse your model row by row, column by column and fill a file with a format like CSV (a row by line and columns separated by coma or tabs).

But, I don't think that is a good idea to modify the file when an item has changed. You should write the file when your application is closed.

Liju G. Chacko

model->item(i,j)->write(stream); will lead to segmentation fault if item(i,j) is empty. Assign some dummy value like whitespace in empty cells.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!