Save QTableWidget



  • Hi all,

    I have built a QTableWidget that the user fills up with numbers. Then it is send via usb 2.0. to a microcontroler.
    I already asked a question here on this "forum":http://qt-project.org/forums/viewthread/23923/#111129 to help me with QtableWidget. It worked perfectly.

    I am now facing another problem... I cannot find how to SAVE the table. It is unaceptable to be unable to save.

    Could you point me in the right direction. I will continue trying to find an example in the meantime!

    Thanks



  • A QTableWidget is essentiall a QTableView with a default, simple, model.
    When you say 'save' you likely mean you want to export the data from this standard model.

    There are two approaches; the hard one is to write your own model using a datastructure you can implement any way you want.

    The suggested, easier solution is to figure out how the default model works and get your data out like that.
    See the model() method on the widget, and use the data() method on the QAbstractItemModel.

    Have fun!



  • Thanks
    Here is what I did.. it works pretty well

    @void MainWindow::saveFile(const QString &name)
    {
    QFile file(name);
    /if (file.open(QIODevice::WriteOnly|QIODevice::Text)) {
    file.write(ui->textEdit->toPlainText().toUtf8());
    statusBar()->showMessage(tr("File saved successfully."), 3000);
    }
    /

    if (file.open(QFile::WriteOnly | QFile::Truncate))
    {
        QTextStream data( &file );
        QStringList strList;
        for( int c = 0; c < ui->tableWidget->columnCount(); ++c )
        {
            strList <<
                       "\" " +
                       ui->tableWidget->horizontalHeaderItem(c)->data(Qt::DisplayRole).toString() +
                       "\" ";
        }
        strList <<
                   "\" " +
                   ui->textEdit->toPlainText().toUtf8() +
                   "\" ";
        data << strList.join(";") << "\n";
        for( int r = 0; r < ui->tableWidget->rowCount(); ++r )
        {
            strList.clear();
            for( int c = 0; c < ui->tableWidget->columnCount(); ++c )
            {   QTableWidgetItem* item = ui->tableWidget->item(r,c);        //Load items
                if (!item || item->text().isEmpty())                        //Test if there is something at item(r,c)
                {
                    ui->tableWidget->setItem(r,c,new QTableWidgetItem("0"));//IF there is nothing write 0
                }
                strList << "\" "+ui->tableWidget->item( r, c )->text()+"\" ";
    
            }
            data << strList.join( ";" )+"\n";
        }
        statusBar()->showMessage(tr("File saved successfully."), 3000);
        file.close();
    }
    

    }@



  • Now I need to LOAD files!!



  • I tried this for loading a .csv file. But I get an exception at line 32. What is the problem?

    @void MainWindow::loadFile()
    {
    //QString filename = QFileDialog::getOpenFileName(this);
    //QFile file(filename);
    /* if (file.open(QIODevice::ReadOnly|QIODevice::Text)) {
    ui->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
    mFilePath = filename;
    statusBar()->showMessage(tr("File successfully loaded."), 3000);
    }/
    QString fileName = QFileDialog::getOpenFileName(this, ("Open File"), NULL, ("csv File(
    .csv)"));
    QString data;
    QFile importedCSV(fileName);
    QStringList rowOfData;
    QStringList rowData;
    data.clear();
    rowOfData.clear();
    rowData.clear();

    if (importedCSV.open(QFile::ReadOnly))
    {
        data = importedCSV.readAll();
        rowOfData = data.split("\n");           //Value on each row
        importedCSV.close();
    }
    
    for (int x = 0; x < rowOfData.size(); x++)  //rowOfData.size() gives the number of row
    {
        rowData = rowOfData.at(x).split(";");   //Number of collumn
        int r=rowData.size();
        for (int y = 0; y < rowData.size(); y++)
        {
            ui->tableWidget->item(x,y)->setText(rowData[y]);
        }
    }
    statusBar()->showMessage(tr("File successfully loaded."), 3000);
    

    }@



  • I have change line 32 with

    @ui->tableWidget->setItem(x-1,y,new QTableWidgetItem(rowData[y]));@

    But the table is filling up with '' Text '' how do remove ''??



  • Ok I found out how.. thanks. Solved

    Note: I had to replace

    @"" " + ui->tableWidget->horizontalHeaderItem(c)->data(Qt::DisplayRole).toString() + "" ";@

    with

    @ui->tableWidget->horizontalHeaderItem(c)->data(Qt::DisplayRole).toString() +
    " ";@



  • excuse me, I know it's been a looong while, but could you tell me what ui->textEdit is? I'm having trouble saving my qtablewidget and this isthe only actual solution I can find, but I don't quite understand it


  • Lifetime Qt Champion

    Hi,

    ui implies that this is a Designer based widget. textEdit is likely to be a QTextEdit

    Hope it helps



  • Hi
    I use code

    for( int r = 0; r < ui->tableWidget->rowCount(); ++r )
        {
            strList.clear();
            for( int c = 0; c < ui->tableWidget->columnCount(); ++c )
            {   QTableWidgetItem* item = ui->tableWidget->item(r,c);     
                if (!item || item->text().isEmpty())                        
                {
                    ui->tableWidget->setItem(r,c,new QTableWidgetItem("0"));
                }
                strList << "\" "+ui->tableWidget->item( r, c )->text()+"\" ";
    
            }
            data << strList.join( ";" )+"\n";
        }
    

    I have problem When I read(Open) file and write(save) file replace again (around 3 round).
    But file has empty line.
    Please help me .


  • Qt Champions 2016

    @hannao
    Hi and welcome
    so you save all rows as
    col;col;col ?

    So what is not working?
    There is empty line ?
    or nothing at all in file ?



  • Yes, when I save again agin again. This file is empty


  • Qt Champions 2016

    @hannao
    can you show the load code ?



  • I implemented something I consider relatively satisfying (even though there's a lot of room for improvement) here: https://github.com/VSRonin/Qt-Model-Serialisation/tree/dev (make sure you use the dev branch)

        CsvModelSerialiser serial; //create the serialiser
        serial->setModel(tableWidget->model()); // set the model to save
        serial->setCsvSeparator(";"); // use ; as separator
        QFile tempFile("TestSave"); // prepare the file to save
        if (!serial->saveModel(&tempFile)) // save the model to file
            Q_ASSERT(false);
    

    to load it:

        CsvModelSerialiser serial; //create the serialiser
        serial->setModel(tableWidget->model()); // set the model to load
        serial->setCsvSeparator(";"); // use ; as separator
        QFile tempFile("TestSave"); // prepare the file to load
        if (!serial->loadModel(&tempFile)) // save the model to file
            Q_ASSERT(false);
    


  • Here I use.

    void Finalline2::on_openButton_clicked()
    {
        QString filename = QFileDialog::getOpenFileName(this,tr("Open Files"),"/home/pi/share/L2/Final Line",tr("Txt Files(*.txt)"));
        QFile file(filename);
        QStringList listA;
        int row=0;
        if(file.open(QIODevice::ReadOnly)){
            while(!file.atEnd()){
                QString line = file.readLine();
                listA = line.split(",");
                ui->tableWidget->setColumnCount(listA.size());
                ui->tableWidget->insertRow(row);
                for(int x = 0; x < listA.size() ; x++)
                {
                    QTableWidgetItem *test = new QTableWidgetItem(listA.at(x));
                    ui->tableWidget->setItem(row, x, test);
                }
                row++;
            }
    
        }
        file.close();
    }
    


  • @hannao said in [SOLVED] Save QTableWidget:

    listA = line.split(",");

    @hannao said in [SOLVED] Save QTableWidget:

    data << strList.join( ";" )+"\n";

    I see something weird going on here


    @hannao said in [SOLVED] Save QTableWidget:

    if(file.open(QIODevice::ReadOnly)){

    If the file is text you should use the text flag if(file.open(QIODevice::ReadOnly | QIODevice::Text)){



  • @VRonin
    I'm sorry. Real I use listA = line.split(" , ");



  • @hannao said in [SOLVED] Save QTableWidget:

    I use listA = line.split(" , ");

    It's still different from the save code

    Did you try using my code?

    You just have to copy everything excluding model_serialisation_global.h into your folder and add DEFINES += QT_MODEL_SERIALISATION_EXPORT to your pro file (I know this is not ideal but if it's still in the dev branch there are reasons)



  • @VRonin
    I use Qt on Rasberry pi3
    but normally when I install use
    qmake
    make
    make install
    but I don't how to install model_serialisation . please suggestion to me.



  • No, do not bother building the library (in fact I don't think it will work as I miss the .pro file altogether). Just copy everything excluding model_serialisation_global.h in your project and add the sources to your project.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.