Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Save QTableWidget
Forum Updated to NodeBB v4.3 + New Features

Save QTableWidget

Scheduled Pinned Locked Moved Solved General and Desktop
20 Posts 7 Posters 24.6k Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    bareil76
    wrote on last edited by A Former User
    #1

    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

    1 Reply Last reply
    0
    • T Offline
      T Offline
      tzander
      wrote on last edited by
      #2

      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!

      1 Reply Last reply
      0
      • B Offline
        B Offline
        bareil76
        wrote on last edited by
        #3

        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();
        }
        

        }@

        1 Reply Last reply
        0
        • B Offline
          B Offline
          bareil76
          wrote on last edited by
          #4

          Now I need to LOAD files!!

          1 Reply Last reply
          0
          • B Offline
            B Offline
            bareil76
            wrote on last edited by
            #5

            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);
            

            }@

            1 Reply Last reply
            0
            • B Offline
              B Offline
              bareil76
              wrote on last edited by
              #6

              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 ''??

              1 Reply Last reply
              0
              • B Offline
                B Offline
                bareil76
                wrote on last edited by
                #7

                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() +
                " ";@

                1 Reply Last reply
                0
                • M Offline
                  M Offline
                  marinamarina
                  wrote on last edited by
                  #8

                  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

                  1 Reply Last reply
                  0
                  • SGaistS Offline
                    SGaistS Offline
                    SGaist
                    Lifetime Qt Champion
                    wrote on last edited by
                    #9

                    Hi,

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

                    Hope it helps

                    Interested in AI ? www.idiap.ch
                    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                    1 Reply Last reply
                    0
                    • H Offline
                      H Offline
                      hannao
                      wrote on last edited by VRonin
                      #10

                      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 .

                      mrjjM 1 Reply Last reply
                      0
                      • H hannao

                        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 .

                        mrjjM Offline
                        mrjjM Offline
                        mrjj
                        Lifetime Qt Champion
                        wrote on last edited by mrjj
                        #11

                        @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 ?

                        1 Reply Last reply
                        0
                        • H Offline
                          H Offline
                          hannao
                          wrote on last edited by
                          #12

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

                          mrjjM 1 Reply Last reply
                          0
                          • H hannao

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

                            mrjjM Offline
                            mrjjM Offline
                            mrjj
                            Lifetime Qt Champion
                            wrote on last edited by
                            #13

                            @hannao
                            can you show the load code ?

                            1 Reply Last reply
                            0
                            • VRoninV Offline
                              VRoninV Offline
                              VRonin
                              wrote on last edited by VRonin
                              #14

                              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);
                              

                              "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                              ~Napoleon Bonaparte

                              On a crusade to banish setIndexWidget() from the holy land of Qt

                              1 Reply Last reply
                              1
                              • H Offline
                                H Offline
                                hannao
                                wrote on last edited by VRonin
                                #15

                                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();
                                }
                                
                                VRoninV 1 Reply Last reply
                                0
                                • H hannao

                                  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();
                                  }
                                  
                                  VRoninV Offline
                                  VRoninV Offline
                                  VRonin
                                  wrote on last edited by
                                  #16

                                  @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)){

                                  "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                  ~Napoleon Bonaparte

                                  On a crusade to banish setIndexWidget() from the holy land of Qt

                                  H 1 Reply Last reply
                                  0
                                  • VRoninV VRonin

                                    @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)){

                                    H Offline
                                    H Offline
                                    hannao
                                    wrote on last edited by
                                    #17

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

                                    VRoninV 1 Reply Last reply
                                    0
                                    • H hannao

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

                                      VRoninV Offline
                                      VRoninV Offline
                                      VRonin
                                      wrote on last edited by VRonin
                                      #18

                                      @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)

                                      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                      ~Napoleon Bonaparte

                                      On a crusade to banish setIndexWidget() from the holy land of Qt

                                      H 1 Reply Last reply
                                      1
                                      • VRoninV VRonin

                                        @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)

                                        H Offline
                                        H Offline
                                        hannao
                                        wrote on last edited by
                                        #19

                                        @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.

                                        1 Reply Last reply
                                        0
                                        • VRoninV Offline
                                          VRoninV Offline
                                          VRonin
                                          wrote on last edited by
                                          #20

                                          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.

                                          "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                          ~Napoleon Bonaparte

                                          On a crusade to banish setIndexWidget() from the holy land of Qt

                                          1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved