Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - reading from a text file

Tags:

qt

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 ?

like image 422
user289175 Avatar asked Apr 10 '10 03:04

user289175


People also ask

How do I display a text file in Qt?

First of all, this is enough: QFile file("farey. txt"); file. open(QFile::ReadOnly | QFile::Text); ui->Output->setPlaintText(file.

How do I read a text file in QML?

You need an actual program to do the rest. Show activity on this post. There is built-in file I/O available for QML with the Felgo SDK (formerly V-Play) FileUtils . It works cross-platform on desktop, iOS and Android.

How do you create a text file in Qt?

Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well. Show activity on this post. It can happen that the cause is not that you don't find the right directory.


1 Answers

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(); 
like image 190
mosg Avatar answered Sep 30 '22 14:09

mosg