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. How to save a table in a file
QtWS25 Last Chance

How to save a table in a file

Scheduled Pinned Locked Moved Unsolved General and Desktop
27 Posts 5 Posters 6.0k Views
  • 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.
  • V Offline
    V Offline
    VRonin
    wrote on 10 Jul 2018, 07:50 last edited by VRonin 4 Sept 2021, 07:38
    #2

    I'm developing a library that includes this feature: https://github.com/VSRonin/QtModelUtilities
    I still need to get it to stable and fully documented but should be good enough for rock and roll.
    Saving to csv is done via the CsvModelSerialiser class

    "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
    • D Offline
      D Offline
      Daesos
      wrote on 10 Jul 2018, 07:59 last edited by
      #3

      I'd like to not implement other libraries. I want to resolve this only with given libraries by Qt.

      V 1 Reply Last reply 10 Jul 2018, 08:18
      0
      • D Daesos
        10 Jul 2018, 07:43

        Hello. I'm new here, but i've already read many topic of this forum.
        I'm creating a program that monitors a directory.
        I've searched for a method to save a tablewidget to a file and this is what I've made:

        void MainWindow::on_pushButton_2_clicked()
        {
        QFile csv("log_activity.csv");
        
        if(!csv.open(QFile::WriteOnly))
            return;
        
        QTextStream out(&csv);
        
        for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
            for (int j = 1; j < ui->tableWidget->columnCount(); j++)
                out<<ui->tableWidget->item(i, j)->text();
        
        csv.close();
        }
        

        This is my tablewidget:

        0_1531208468134_7dddbc22-3ed3-431d-99d3-0f05a3a3dc79-image.png

        The problem is that once i click on the save button (pushButton_2) the program doesn't save anything in the file. What am i missing?

        J Offline
        J Offline
        jsulm
        Lifetime Qt Champion
        wrote on 10 Jul 2018, 08:06 last edited by
        #4

        @Daesos Are you sure it does not save the file? You're using a relative path, that means the file will be located in the current working directory of your app, most probably in the build directory. Also did you check whether MainWindow::on_pushButton_2_clicked() was actually called?

        https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply
        1
        • D Offline
          D Offline
          Daesos
          wrote on 10 Jul 2018, 08:13 last edited by Daesos 7 Oct 2018, 08:16
          #5

          The image above is the directory of my project. If I click on save button, the cell corresponding to log_activity.csv and Event changes into modified.
          It shows "Modified" when the date of the previous directory is different from the current one.
          So I guess the save_button works.

          0_1531210402194_729a0dca-9bc9-4745-a532-9d41af2aef78-image.png

          Also, if the file doesn't exit, the program create the file with the given name.

          J J 2 Replies Last reply 10 Jul 2018, 08:21
          0
          • D Daesos
            10 Jul 2018, 07:59

            I'd like to not implement other libraries. I want to resolve this only with given libraries by Qt.

            V Offline
            V Offline
            VRonin
            wrote on 10 Jul 2018, 08:18 last edited by VRonin 7 Oct 2018, 08:21
            #6

            @Daesos said in How to save a table in a file:

            I want to resolve this only with given libraries by Qt

            Then copy-paste my code. I only use Qt in those and license is apache 2 so you can basically do what you want with it.

            In your code above you are not:

            • Writing any new line to separate rows.
            • Writing any column separator
            • Escaping column separators inside the data

            "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
            • D Daesos
              10 Jul 2018, 08:13

              The image above is the directory of my project. If I click on save button, the cell corresponding to log_activity.csv and Event changes into modified.
              It shows "Modified" when the date of the previous directory is different from the current one.
              So I guess the save_button works.

              0_1531210402194_729a0dca-9bc9-4745-a532-9d41af2aef78-image.png

              Also, if the file doesn't exit, the program create the file with the given name.

              J Offline
              J Offline
              jsulm
              Lifetime Qt Champion
              wrote on 10 Jul 2018, 08:21 last edited by
              #7

              @Daesos Did you try to debug? Especially the nested for loops?

              https://forum.qt.io/topic/113070/qt-code-of-conduct

              D 1 Reply Last reply 10 Jul 2018, 09:55
              0
              • D Daesos
                10 Jul 2018, 08:13

                The image above is the directory of my project. If I click on save button, the cell corresponding to log_activity.csv and Event changes into modified.
                It shows "Modified" when the date of the previous directory is different from the current one.
                So I guess the save_button works.

                0_1531210402194_729a0dca-9bc9-4745-a532-9d41af2aef78-image.png

                Also, if the file doesn't exit, the program create the file with the given name.

                J Offline
                J Offline
                JonB
                wrote on 10 Jul 2018, 08:23 last edited by JonB 7 Oct 2018, 08:24
                #8

                @Daesos
                Assuming the file is opened for write, you are saying you end up with nothing in it, and your table does indeed contain desired text (ui->tableWidget->item(i, j)->text()). You stream all your data to QTextStream out but you only close the QFile csv. I don't know if that knows to fetch all remaining data out of the stream. Try out.flush() prior to the csv.close()?

                1 Reply Last reply
                1
                • J jsulm
                  10 Jul 2018, 08:21

                  @Daesos Did you try to debug? Especially the nested for loops?

                  D Offline
                  D Offline
                  Daesos
                  wrote on 10 Jul 2018, 09:55 last edited by Daesos 7 Oct 2018, 09:58
                  #9

                  @jsulm I'm trying, but it stops with this message: Stopped "end-stepping-range". I've put a breakpoint at "out<<ui->tableWidget->item(i, j)->text();" and as i can see, this returns "main.window.cpp", which is correct. Then, I don't what happen.

                  J 1 Reply Last reply 10 Jul 2018, 10:37
                  0
                  • D Daesos
                    10 Jul 2018, 09:55

                    @jsulm I'm trying, but it stops with this message: Stopped "end-stepping-range". I've put a breakpoint at "out<<ui->tableWidget->item(i, j)->text();" and as i can see, this returns "main.window.cpp", which is correct. Then, I don't what happen.

                    J Offline
                    J Offline
                    jsulm
                    Lifetime Qt Champion
                    wrote on 10 Jul 2018, 10:37 last edited by
                    #10

                    @Daesos Try calling http://doc.qt.io/qt-5/qtextstream.html#flush before closing the file

                    https://forum.qt.io/topic/113070/qt-code-of-conduct

                    D 1 Reply Last reply 10 Jul 2018, 10:41
                    0
                    • J jsulm
                      10 Jul 2018, 10:37

                      @Daesos Try calling http://doc.qt.io/qt-5/qtextstream.html#flush before closing the file

                      D Offline
                      D Offline
                      Daesos
                      wrote on 10 Jul 2018, 10:41 last edited by
                      #11

                      @jsulm Already did, and nothing changed.

                      J 1 Reply Last reply 10 Jul 2018, 10:45
                      0
                      • D Daesos
                        10 Jul 2018, 10:41

                        @jsulm Already did, and nothing changed.

                        J Offline
                        J Offline
                        jsulm
                        Lifetime Qt Champion
                        wrote on 10 Jul 2018, 10:45 last edited by
                        #12

                        @Daesos Last idea I have: is it possible that you open same file somewhere else in your app, or that there is still an instance of your app running?
                        Oh, one more idea: try to write the file using an absolute path to some other location.

                        https://forum.qt.io/topic/113070/qt-code-of-conduct

                        D 1 Reply Last reply 10 Jul 2018, 11:06
                        0
                        • J jsulm
                          10 Jul 2018, 10:45

                          @Daesos Last idea I have: is it possible that you open same file somewhere else in your app, or that there is still an instance of your app running?
                          Oh, one more idea: try to write the file using an absolute path to some other location.

                          D Offline
                          D Offline
                          Daesos
                          wrote on 10 Jul 2018, 11:06 last edited by Daesos 7 Oct 2018, 11:09
                          #13

                          @jsulm I checked and there is no other instance opened. Also, I used another path. The program created the file.csv (empty), then quitted. Application Output: "The program has unexpectedly finished."

                          Since I don't know if I have mistaken something I will post all the mainwindow.cpp code:

                          #include "mainwindow.h"
                          #include "ui_mainwindow.h"
                          #include <QFileDialog>
                          #include <QFileInfo>
                          #include <QTimer>
                          #include <QDateTime>
                          #include <QFile>
                          #include <QTextStream>
                          
                          MainWindow::MainWindow(QWidget *parent) :
                              QMainWindow(parent),
                              ui(new Ui::MainWindow)
                          {
                              ui->setupUi(this);
                          
                              setWindowTitle("DirectoryMonitor");
                              ui->tableWidget->setColumnCount(4);
                              ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "" << "Filename" << "Event" << "Time");
                          
                              f_name = "log_activity.csv";
                          }
                          
                          MainWindow::~MainWindow()
                          {
                              delete ui;
                          }
                          
                          void MainWindow::on_pushButton_clicked()
                          {
                              ui->tableWidget->clearContents();
                              path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), ".", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                              ui->lineEdit->setText(path);
                          
                          QDir dir(path);
                          
                          dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                          dir.setSorting(QDir::Time);
                          list = dir.entryInfoList();
                          
                          for(int i = 0; i < list.size(); ++i){
                                  ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                  ui->tableWidget->setItem(i, 1, new QTableWidgetItem(list.at(i).fileName()));
                                  ui->tableWidget->setItem(i, 3, new QTableWidgetItem(list.at(i).lastModified().toString()));
                          }
                          
                          int count = 0;
                          
                          for(int i = 0; i < ui->tableWidget->rowCount(); ++i){
                              QTableWidgetItem *itm = ui->tableWidget->item(i, 1);
                              if(itm != 0)
                                 ++count;
                          }
                          //rimuovi righe vuote
                          ui->tableWidget->setRowCount(count);
                          
                          QTimer *time = new QTimer(this);
                          
                          connect(time, SIGNAL(timeout()), this, SLOT(changes()));
                          time->start(3000);
                          }
                          
                          void MainWindow::changes()
                          {
                          QDir dir(path);
                          dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                          dir.setSorting(QDir::Time);
                          
                          QFileInfoList newlist = dir.entryInfoList();
                          
                          int index_delete = -1;
                          
                          //caso modified e delete file
                          for(int i = 0; i < list.size(); ++i){
                              int count = 0;
                              for(int j = 0; j < newlist.size(); ++j){
                                  if(list.at(i).fileName() == newlist.at(j).fileName()){
                                      ++count;
                                      if(list.at(i).lastModified() != newlist.at(j).lastModified()){
                                          QTableWidgetItem *itm = new QTableWidgetItem("");
                                          itm->setBackground(QColor(109, 158, 235));
                                          ui->tableWidget->setItem(i, 0, itm);
                                          ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                          ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                      }
                                  }
                              }
                              if(count == 0){
                                  index_delete = i;
                              }
                          }
                          
                          if(index_delete != -1){
                              QTableWidgetItem *itm = new QTableWidgetItem("");
                              itm->setBackground(QColor(224, 102, 99));
                              ui->tableWidget->setItem(index_delete, 0, itm);
                              if(ui->tableWidget->item(index_delete, 2)->text() != "Deleted")
                                  ui->tableWidget->setItem(index_delete, 3, new QTableWidgetItem(QDateTime::currentDateTime().toString()));
                              ui->tableWidget->setItem(index_delete, 2, new QTableWidgetItem("Deleted"));
                          }
                          
                          //caso new file
                          int index_new = -1;
                          
                          for(int i = 0; i < newlist.size(); ++i){
                              int count = 0;
                              for(int j = 0; (j < list.size() && count == 0); ++j){
                                  if(newlist.at(i).fileName() == list.at(j).fileName())
                                      ++count;
                              }
                              if(count == 0)
                                  index_new = i;
                          }
                          
                          if(index_new != -1){
                              ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                              QTableWidgetItem *itm = new QTableWidgetItem("");
                              itm->setBackground(QColor(148, 195, 123));
                              ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, itm);
                              ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));
                              ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, new QTableWidgetItem("Created"));
                              ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, new QTableWidgetItem(newlist.at(index_new).lastModified().toString()));
                              list.append(newlist.at(index_new));
                          }
                          }
                          void MainWindow::on_pushButton_2_clicked()
                          {
                          QFile csv(f_name);
                          
                          if(!csv.open(QFile::WriteOnly))
                              return;
                          
                          QTextStream out(&csv);
                          
                          for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                              for (int j = 1; j < ui->tableWidget->columnCount(); j++){
                                  QString txt(ui->tableWidget->item(i, j)->text());
                                  out<<txt;
                              }
                          out.flush();
                          csv.close();
                          }
                          

                          Sorry for the indentation.
                          This is the declaration of the global variables in mainwindow.h

                          QString path, f_name;
                          QFileInfoList list;
                          
                          J J J 3 Replies Last reply 10 Jul 2018, 11:10
                          0
                          • D Daesos
                            10 Jul 2018, 11:06

                            @jsulm I checked and there is no other instance opened. Also, I used another path. The program created the file.csv (empty), then quitted. Application Output: "The program has unexpectedly finished."

                            Since I don't know if I have mistaken something I will post all the mainwindow.cpp code:

                            #include "mainwindow.h"
                            #include "ui_mainwindow.h"
                            #include <QFileDialog>
                            #include <QFileInfo>
                            #include <QTimer>
                            #include <QDateTime>
                            #include <QFile>
                            #include <QTextStream>
                            
                            MainWindow::MainWindow(QWidget *parent) :
                                QMainWindow(parent),
                                ui(new Ui::MainWindow)
                            {
                                ui->setupUi(this);
                            
                                setWindowTitle("DirectoryMonitor");
                                ui->tableWidget->setColumnCount(4);
                                ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "" << "Filename" << "Event" << "Time");
                            
                                f_name = "log_activity.csv";
                            }
                            
                            MainWindow::~MainWindow()
                            {
                                delete ui;
                            }
                            
                            void MainWindow::on_pushButton_clicked()
                            {
                                ui->tableWidget->clearContents();
                                path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), ".", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                                ui->lineEdit->setText(path);
                            
                            QDir dir(path);
                            
                            dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                            dir.setSorting(QDir::Time);
                            list = dir.entryInfoList();
                            
                            for(int i = 0; i < list.size(); ++i){
                                    ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                    ui->tableWidget->setItem(i, 1, new QTableWidgetItem(list.at(i).fileName()));
                                    ui->tableWidget->setItem(i, 3, new QTableWidgetItem(list.at(i).lastModified().toString()));
                            }
                            
                            int count = 0;
                            
                            for(int i = 0; i < ui->tableWidget->rowCount(); ++i){
                                QTableWidgetItem *itm = ui->tableWidget->item(i, 1);
                                if(itm != 0)
                                   ++count;
                            }
                            //rimuovi righe vuote
                            ui->tableWidget->setRowCount(count);
                            
                            QTimer *time = new QTimer(this);
                            
                            connect(time, SIGNAL(timeout()), this, SLOT(changes()));
                            time->start(3000);
                            }
                            
                            void MainWindow::changes()
                            {
                            QDir dir(path);
                            dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                            dir.setSorting(QDir::Time);
                            
                            QFileInfoList newlist = dir.entryInfoList();
                            
                            int index_delete = -1;
                            
                            //caso modified e delete file
                            for(int i = 0; i < list.size(); ++i){
                                int count = 0;
                                for(int j = 0; j < newlist.size(); ++j){
                                    if(list.at(i).fileName() == newlist.at(j).fileName()){
                                        ++count;
                                        if(list.at(i).lastModified() != newlist.at(j).lastModified()){
                                            QTableWidgetItem *itm = new QTableWidgetItem("");
                                            itm->setBackground(QColor(109, 158, 235));
                                            ui->tableWidget->setItem(i, 0, itm);
                                            ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                            ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                        }
                                    }
                                }
                                if(count == 0){
                                    index_delete = i;
                                }
                            }
                            
                            if(index_delete != -1){
                                QTableWidgetItem *itm = new QTableWidgetItem("");
                                itm->setBackground(QColor(224, 102, 99));
                                ui->tableWidget->setItem(index_delete, 0, itm);
                                if(ui->tableWidget->item(index_delete, 2)->text() != "Deleted")
                                    ui->tableWidget->setItem(index_delete, 3, new QTableWidgetItem(QDateTime::currentDateTime().toString()));
                                ui->tableWidget->setItem(index_delete, 2, new QTableWidgetItem("Deleted"));
                            }
                            
                            //caso new file
                            int index_new = -1;
                            
                            for(int i = 0; i < newlist.size(); ++i){
                                int count = 0;
                                for(int j = 0; (j < list.size() && count == 0); ++j){
                                    if(newlist.at(i).fileName() == list.at(j).fileName())
                                        ++count;
                                }
                                if(count == 0)
                                    index_new = i;
                            }
                            
                            if(index_new != -1){
                                ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                QTableWidgetItem *itm = new QTableWidgetItem("");
                                itm->setBackground(QColor(148, 195, 123));
                                ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, itm);
                                ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));
                                ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, new QTableWidgetItem("Created"));
                                ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, new QTableWidgetItem(newlist.at(index_new).lastModified().toString()));
                                list.append(newlist.at(index_new));
                            }
                            }
                            void MainWindow::on_pushButton_2_clicked()
                            {
                            QFile csv(f_name);
                            
                            if(!csv.open(QFile::WriteOnly))
                                return;
                            
                            QTextStream out(&csv);
                            
                            for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                for (int j = 1; j < ui->tableWidget->columnCount(); j++){
                                    QString txt(ui->tableWidget->item(i, j)->text());
                                    out<<txt;
                                }
                            out.flush();
                            csv.close();
                            }
                            

                            Sorry for the indentation.
                            This is the declaration of the global variables in mainwindow.h

                            QString path, f_name;
                            QFileInfoList list;
                            
                            J Offline
                            J Offline
                            jsulm
                            Lifetime Qt Champion
                            wrote on 10 Jul 2018, 11:10 last edited by
                            #14

                            @Daesos Start your app with debugger (F5) and when it crashes check the stack trace to see where it crashes (use debug build of your app).

                            https://forum.qt.io/topic/113070/qt-code-of-conduct

                            1 Reply Last reply
                            0
                            • D Daesos
                              10 Jul 2018, 11:06

                              @jsulm I checked and there is no other instance opened. Also, I used another path. The program created the file.csv (empty), then quitted. Application Output: "The program has unexpectedly finished."

                              Since I don't know if I have mistaken something I will post all the mainwindow.cpp code:

                              #include "mainwindow.h"
                              #include "ui_mainwindow.h"
                              #include <QFileDialog>
                              #include <QFileInfo>
                              #include <QTimer>
                              #include <QDateTime>
                              #include <QFile>
                              #include <QTextStream>
                              
                              MainWindow::MainWindow(QWidget *parent) :
                                  QMainWindow(parent),
                                  ui(new Ui::MainWindow)
                              {
                                  ui->setupUi(this);
                              
                                  setWindowTitle("DirectoryMonitor");
                                  ui->tableWidget->setColumnCount(4);
                                  ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "" << "Filename" << "Event" << "Time");
                              
                                  f_name = "log_activity.csv";
                              }
                              
                              MainWindow::~MainWindow()
                              {
                                  delete ui;
                              }
                              
                              void MainWindow::on_pushButton_clicked()
                              {
                                  ui->tableWidget->clearContents();
                                  path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), ".", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                                  ui->lineEdit->setText(path);
                              
                              QDir dir(path);
                              
                              dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                              dir.setSorting(QDir::Time);
                              list = dir.entryInfoList();
                              
                              for(int i = 0; i < list.size(); ++i){
                                      ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                      ui->tableWidget->setItem(i, 1, new QTableWidgetItem(list.at(i).fileName()));
                                      ui->tableWidget->setItem(i, 3, new QTableWidgetItem(list.at(i).lastModified().toString()));
                              }
                              
                              int count = 0;
                              
                              for(int i = 0; i < ui->tableWidget->rowCount(); ++i){
                                  QTableWidgetItem *itm = ui->tableWidget->item(i, 1);
                                  if(itm != 0)
                                     ++count;
                              }
                              //rimuovi righe vuote
                              ui->tableWidget->setRowCount(count);
                              
                              QTimer *time = new QTimer(this);
                              
                              connect(time, SIGNAL(timeout()), this, SLOT(changes()));
                              time->start(3000);
                              }
                              
                              void MainWindow::changes()
                              {
                              QDir dir(path);
                              dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                              dir.setSorting(QDir::Time);
                              
                              QFileInfoList newlist = dir.entryInfoList();
                              
                              int index_delete = -1;
                              
                              //caso modified e delete file
                              for(int i = 0; i < list.size(); ++i){
                                  int count = 0;
                                  for(int j = 0; j < newlist.size(); ++j){
                                      if(list.at(i).fileName() == newlist.at(j).fileName()){
                                          ++count;
                                          if(list.at(i).lastModified() != newlist.at(j).lastModified()){
                                              QTableWidgetItem *itm = new QTableWidgetItem("");
                                              itm->setBackground(QColor(109, 158, 235));
                                              ui->tableWidget->setItem(i, 0, itm);
                                              ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                              ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                          }
                                      }
                                  }
                                  if(count == 0){
                                      index_delete = i;
                                  }
                              }
                              
                              if(index_delete != -1){
                                  QTableWidgetItem *itm = new QTableWidgetItem("");
                                  itm->setBackground(QColor(224, 102, 99));
                                  ui->tableWidget->setItem(index_delete, 0, itm);
                                  if(ui->tableWidget->item(index_delete, 2)->text() != "Deleted")
                                      ui->tableWidget->setItem(index_delete, 3, new QTableWidgetItem(QDateTime::currentDateTime().toString()));
                                  ui->tableWidget->setItem(index_delete, 2, new QTableWidgetItem("Deleted"));
                              }
                              
                              //caso new file
                              int index_new = -1;
                              
                              for(int i = 0; i < newlist.size(); ++i){
                                  int count = 0;
                                  for(int j = 0; (j < list.size() && count == 0); ++j){
                                      if(newlist.at(i).fileName() == list.at(j).fileName())
                                          ++count;
                                  }
                                  if(count == 0)
                                      index_new = i;
                              }
                              
                              if(index_new != -1){
                                  ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                  QTableWidgetItem *itm = new QTableWidgetItem("");
                                  itm->setBackground(QColor(148, 195, 123));
                                  ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, itm);
                                  ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));
                                  ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, new QTableWidgetItem("Created"));
                                  ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, new QTableWidgetItem(newlist.at(index_new).lastModified().toString()));
                                  list.append(newlist.at(index_new));
                              }
                              }
                              void MainWindow::on_pushButton_2_clicked()
                              {
                              QFile csv(f_name);
                              
                              if(!csv.open(QFile::WriteOnly))
                                  return;
                              
                              QTextStream out(&csv);
                              
                              for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                  for (int j = 1; j < ui->tableWidget->columnCount(); j++){
                                      QString txt(ui->tableWidget->item(i, j)->text());
                                      out<<txt;
                                  }
                              out.flush();
                              csv.close();
                              }
                              

                              Sorry for the indentation.
                              This is the declaration of the global variables in mainwindow.h

                              QString path, f_name;
                              QFileInfoList list;
                              
                              J Offline
                              J Offline
                              J.Hilk
                              Moderators
                              wrote on 10 Jul 2018, 11:14 last edited by
                              #15

                              @Daesos
                              Going through your code, I noticed, you're mixing postfix, prefix in your nested loop to access the Tablewidget Item. I would search there for an out of bounds error.


                              Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                              Q: What's that?
                              A: It's blue light.
                              Q: What does it do?
                              A: It turns blue.

                              1 Reply Last reply
                              1
                              • D Daesos
                                10 Jul 2018, 11:06

                                @jsulm I checked and there is no other instance opened. Also, I used another path. The program created the file.csv (empty), then quitted. Application Output: "The program has unexpectedly finished."

                                Since I don't know if I have mistaken something I will post all the mainwindow.cpp code:

                                #include "mainwindow.h"
                                #include "ui_mainwindow.h"
                                #include <QFileDialog>
                                #include <QFileInfo>
                                #include <QTimer>
                                #include <QDateTime>
                                #include <QFile>
                                #include <QTextStream>
                                
                                MainWindow::MainWindow(QWidget *parent) :
                                    QMainWindow(parent),
                                    ui(new Ui::MainWindow)
                                {
                                    ui->setupUi(this);
                                
                                    setWindowTitle("DirectoryMonitor");
                                    ui->tableWidget->setColumnCount(4);
                                    ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "" << "Filename" << "Event" << "Time");
                                
                                    f_name = "log_activity.csv";
                                }
                                
                                MainWindow::~MainWindow()
                                {
                                    delete ui;
                                }
                                
                                void MainWindow::on_pushButton_clicked()
                                {
                                    ui->tableWidget->clearContents();
                                    path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), ".", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                                    ui->lineEdit->setText(path);
                                
                                QDir dir(path);
                                
                                dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                                dir.setSorting(QDir::Time);
                                list = dir.entryInfoList();
                                
                                for(int i = 0; i < list.size(); ++i){
                                        ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(list.at(i).fileName()));
                                        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(list.at(i).lastModified().toString()));
                                }
                                
                                int count = 0;
                                
                                for(int i = 0; i < ui->tableWidget->rowCount(); ++i){
                                    QTableWidgetItem *itm = ui->tableWidget->item(i, 1);
                                    if(itm != 0)
                                       ++count;
                                }
                                //rimuovi righe vuote
                                ui->tableWidget->setRowCount(count);
                                
                                QTimer *time = new QTimer(this);
                                
                                connect(time, SIGNAL(timeout()), this, SLOT(changes()));
                                time->start(3000);
                                }
                                
                                void MainWindow::changes()
                                {
                                QDir dir(path);
                                dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                                dir.setSorting(QDir::Time);
                                
                                QFileInfoList newlist = dir.entryInfoList();
                                
                                int index_delete = -1;
                                
                                //caso modified e delete file
                                for(int i = 0; i < list.size(); ++i){
                                    int count = 0;
                                    for(int j = 0; j < newlist.size(); ++j){
                                        if(list.at(i).fileName() == newlist.at(j).fileName()){
                                            ++count;
                                            if(list.at(i).lastModified() != newlist.at(j).lastModified()){
                                                QTableWidgetItem *itm = new QTableWidgetItem("");
                                                itm->setBackground(QColor(109, 158, 235));
                                                ui->tableWidget->setItem(i, 0, itm);
                                                ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                                ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                            }
                                        }
                                    }
                                    if(count == 0){
                                        index_delete = i;
                                    }
                                }
                                
                                if(index_delete != -1){
                                    QTableWidgetItem *itm = new QTableWidgetItem("");
                                    itm->setBackground(QColor(224, 102, 99));
                                    ui->tableWidget->setItem(index_delete, 0, itm);
                                    if(ui->tableWidget->item(index_delete, 2)->text() != "Deleted")
                                        ui->tableWidget->setItem(index_delete, 3, new QTableWidgetItem(QDateTime::currentDateTime().toString()));
                                    ui->tableWidget->setItem(index_delete, 2, new QTableWidgetItem("Deleted"));
                                }
                                
                                //caso new file
                                int index_new = -1;
                                
                                for(int i = 0; i < newlist.size(); ++i){
                                    int count = 0;
                                    for(int j = 0; (j < list.size() && count == 0); ++j){
                                        if(newlist.at(i).fileName() == list.at(j).fileName())
                                            ++count;
                                    }
                                    if(count == 0)
                                        index_new = i;
                                }
                                
                                if(index_new != -1){
                                    ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                                    QTableWidgetItem *itm = new QTableWidgetItem("");
                                    itm->setBackground(QColor(148, 195, 123));
                                    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, itm);
                                    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));
                                    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, new QTableWidgetItem("Created"));
                                    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, new QTableWidgetItem(newlist.at(index_new).lastModified().toString()));
                                    list.append(newlist.at(index_new));
                                }
                                }
                                void MainWindow::on_pushButton_2_clicked()
                                {
                                QFile csv(f_name);
                                
                                if(!csv.open(QFile::WriteOnly))
                                    return;
                                
                                QTextStream out(&csv);
                                
                                for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                    for (int j = 1; j < ui->tableWidget->columnCount(); j++){
                                        QString txt(ui->tableWidget->item(i, j)->text());
                                        out<<txt;
                                    }
                                out.flush();
                                csv.close();
                                }
                                

                                Sorry for the indentation.
                                This is the declaration of the global variables in mainwindow.h

                                QString path, f_name;
                                QFileInfoList list;
                                
                                J Offline
                                J Offline
                                JonB
                                wrote on 10 Jul 2018, 11:38 last edited by JonB 7 Oct 2018, 11:39
                                #16

                                @Daesos
                                If you're still having problems with the file (once you've solved the "crash"), try replacing your QFile with a QString, and use https://doc.qt.io/Qt-5/qtextstream.html#QTextStream-3. You should be successfully building up the string of the file content. If that doesn't work, nor will write to file.

                                1 Reply Last reply
                                0
                                • D Offline
                                  D Offline
                                  Daesos
                                  wrote on 10 Jul 2018, 11:39 last edited by Daesos 7 Oct 2018, 11:52
                                  #17

                                  I used debugger and when i click on pushButton_2 (save on interface) it returns a Segmentation Fault at "QTableWidgetItem::text".
                                  @J.Hilk, I didn't even notice. I edited the increment.

                                  Segmentation Fault occurs when I try to access to a NULL pointer, right? So, it might be out of bound.

                                  J 1 Reply Last reply 10 Jul 2018, 11:40
                                  0
                                  • D Daesos
                                    10 Jul 2018, 11:39

                                    I used debugger and when i click on pushButton_2 (save on interface) it returns a Segmentation Fault at "QTableWidgetItem::text".
                                    @J.Hilk, I didn't even notice. I edited the increment.

                                    Segmentation Fault occurs when I try to access to a NULL pointer, right? So, it might be out of bound.

                                    J Offline
                                    J Offline
                                    JonB
                                    wrote on 10 Jul 2018, 11:40 last edited by JonB 7 Oct 2018, 11:46
                                    #18

                                    @Daesos
                                    I don't see save_button in the code you've posted?

                                    I notice you have:

                                                    ui->tableWidget->setItem(i, 0, itm);
                                                    ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                                    ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                    

                                    Where do you setItem() on i, 1 ?

                                    for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                        for (int j = 1; j < ui->tableWidget->columnCount(); j++){
                                            QString txt(ui->tableWidget->item(i, j)->text());
                                            out<<txt;
                                        }
                                    

                                    Check your accesses on every i, j here. Somewhere you do not have an item at item(i, j)!

                                    1 Reply Last reply
                                    0
                                    • D Offline
                                      D Offline
                                      Daesos
                                      wrote on 10 Jul 2018, 11:50 last edited by Daesos 7 Oct 2018, 11:53
                                      #19

                                      I've edited the increment:

                                         for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                             for (int j = 1; j < ui->tableWidget->columnCount(); ++j)
                                                 out<<ui->tableWidget->item(i, j)->text();
                                      

                                      @JonB said in How to save a table in a file:

                                      @Daesos

                                      I notice you have:

                                                      ui->tableWidget->setItem(i, 0, itm);
                                                      ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                                      ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                      

                                      Where do you setItem() on i, 1 ?

                                      I've inizialized item at (i, 1) before. Once inizialized the name of the file must not be modified. So I didn't use setItem on i, 1 again.

                                      @Daesos
                                      ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));

                                      J 1 Reply Last reply 10 Jul 2018, 11:59
                                      0
                                      • D Daesos
                                        10 Jul 2018, 11:50

                                        I've edited the increment:

                                           for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                               for (int j = 1; j < ui->tableWidget->columnCount(); ++j)
                                                   out<<ui->tableWidget->item(i, j)->text();
                                        

                                        @JonB said in How to save a table in a file:

                                        @Daesos

                                        I notice you have:

                                                        ui->tableWidget->setItem(i, 0, itm);
                                                        ui->tableWidget->setItem(i, 2, new QTableWidgetItem("Modified"));
                                                        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(newlist.at(j).lastModified().toString()));
                                        

                                        Where do you setItem() on i, 1 ?

                                        I've inizialized item at (i, 1) before. Once inizialized the name of the file must not be modified. So I didn't use setItem on i, 1 again.

                                        @Daesos
                                        ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(newlist.at(index_new).fileName()));

                                        J Offline
                                        J Offline
                                        J.Hilk
                                        Moderators
                                        wrote on 10 Jul 2018, 11:59 last edited by
                                        #20

                                        @Daesos said in How to save a table in a file:

                                        for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                        for (int j = 1; j < ui->tableWidget->columnCount(); ++j)
                                        out<<ui->tableWidget->item(i, j)->text();

                                        Maybe it's time to #include good old <QDebug>

                                        for(int i = 0; i < ui->tableWidget->rowCount(); ++i)
                                               for (int j = 1; j < ui->tableWidget->columnCount(); ++j){
                                                   qDebug() << i << "of" << ui->tableWidget->rowCount() << endl
                                                                     << j << "of" << ui->tableWidget->columnCount();
                                                   out<<ui->tableWidget->item(i, j)->text();
                                                   qDebug() << QString("Found text at %1 | %2").arg(i).arg(j);
                                               }
                                        

                                        Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                        Q: What's that?
                                        A: It's blue light.
                                        Q: What does it do?
                                        A: It turns blue.

                                        1 Reply Last reply
                                        0
                                        • V Offline
                                          V Offline
                                          VRonin
                                          wrote on 10 Jul 2018, 12:00 last edited by VRonin 7 Oct 2018, 12:00
                                          #21

                                          Replace out<<ui->tableWidget->item(i, j)->text(); with out<<ui->tableWidget->model()->index(i, j).data().tostring(); to prevent segfaults

                                          The problems I highlighted are still present though

                                          @VRonin said in How to save a table in a file:

                                          In your code above you are not:

                                          • Writing any new line to separate rows.
                                          • Writing any column separator
                                          • Escaping column separators inside the data

                                          "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

                                          D 1 Reply Last reply 10 Jul 2018, 12:53
                                          3

                                          11/27

                                          10 Jul 2018, 10:41

                                          • Login

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