28

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 ?

0

2 Answers 2

96

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();
3
  • 1
    his bug seemed to also be that he wasn't calling file.open again like you do in your code.
    – NG.
    Apr 10, 2010 at 13:58
  • Thanks all, I need more efforts. there is an error error “no matching function for call to ‘QStandardItemModel::appendRow(QStringList&)’”
    – user289175
    Apr 11, 2010 at 6:01
  • 3
    @ user289175 : And again, you have to read Qt docs (for example, Qt Assistant). In QStandardItemModel class this is no QStandardItemModel::appendRow(QStringList&) member, but appendRow ( const QList<QStandardItem *> & ) & appendRow ( QStandardItem * ) has.
    – mosg
    Apr 12, 2010 at 6:09
0

You couldn't reopen the first file to read data because the first file was never closed. Close the first file then you will be able to reopen it to read data.

1
  • You can open the same file several times for reading. In this case, the second code does not open it hence the issue. It's a different QFile object.
    – SGaist
    Aug 19 at 12:55

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.