0

I'm very new to QT and I have an application which has a QTableWidget in it and I want to add save and load option to my application. the question is how to save and load data in QTableWidget. I found this page:http://doc.qt.io/qt-5/qtwidgets-tutorials-addressbook-part6-example.html#defining-the-addressbook-class but it wasn't useful:I tried a code like this to save:

void training::on_pushButton_3_clicked()
{
    QVector<QTableWidgetItem*> outvector;
    for(int i = 0;i<ui->tableWidget->rowCount();i++)
        for(int ii=0;i<ui->tableWidget->columnCount();ii++)
            outvector.append(ui->tableWidget->item(i,ii));
    QString path = QFileDialog::getSaveFileName(this,QString("Save file     path"),"",QString("table (*.tbl);;All Files (*)"));
    if(path.isEmpty())
        return;
    else{
        QFile file(path);
        if(!file.open(QIODevice::WriteOnly)){
            QMessageBox::information(this,"Error",file.errorString());
            return;
        }
        else{
            QDataStream out(&file);
            out.setVersion(QDataStream::Qt_5_11);
            out<<outvector;
        }
    }
}

Is this right?! If it works how to load the information again; if not how to save and load data in tablewidget?

Any help would be appreciated.

Angel
  • 11
  • 4

2 Answers2

0

Make this correction to your code:

...
for(int ii=0;ii<ui->tableWidget->columnCount();ii++)
...

For this (save and load data in QTableWidget) look at Serialization with Qt, So you need to consider what exactly you want to Save/load (serialize). since QVector is serializable, I think your code won't complain, but indeed it won't store your actual data, QTableWidgetItems, because that data type is not in list of serializable types - try to directly save an individual item and you will know what errors will come. Moreover, serializing compound types (vector of table items) may not be the right approach even if both types are supported.

In order to solve your issue, you need to serialize whatever data you store in your QTableWidget items, for example read text from item and store ...etc.

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
0

Thanks it's fixed up using

item.write(outstream);

I saved everyitem using write function then with same order I used read function item.read(instream) to load it again.

Angel
  • 11
  • 4