27
votes

I have a table view with three columns; I have just passed to write into text file using this code

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::WriteOnly)) {
    QMessageBox::information(0,"error",file.errorString());
}
QString dd;

for(int row=0; row < model->rowCount(); row++) {
     dd = model->item(row,0)->text() +  ","
                 + model->item(row,1)->text() +  ","
                 + model->item(row,2)->text();

     QTextStream out(&file);
     out << dd << endl;
 }

But I'm not succeed to read the same file again, I tried this code but I don't know where is the problem in it

QFile file("/home/hamad/lesson11.txt");
QTextStream in(&file);
QString line = in.readLine();
while(!in.atEnd()) {

    QStringList  fields = line.split(",");

    model->appendRow(fields);

}

Any help please ?

1
Do you open the file again like you did the first time? I think that might be your issue.NG.
I couldn't open the file from Qt; but I'm sure the writing function is working perfectly by open the txt file using geedit. Any help ??user289175
mosg has a good point above, but my question was why aren't you calling file.open again before trying to read your file? You do it before writing it, so why wouldn't you have to do it before reading it? Your code in the post doesn't do that.NG.
I don't want to open the text file, I want to read the data what are in the text file then bind them into tableviewuser289175
You have to open the file to start reading it. Look at your code closely. When you write data, you first call file.open(QIODevice::WriteOnly) and then write data to it. Similarly, to get data out of a file, you will need to call file.open(QIODevice::ReadOnly) and then read the data. You can do whatever you want with the data after that. These are standard operations when doing File IO in most languages.NG.

1 Answers

93
votes

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();