Qt - 从文本文件中读取

时间:2010-04-10 03:16:21

标签: qt

我有一个包含三列的表视图;我刚刚使用此代码

传递写入文本文件
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;
 }

但是我没有成功再次阅读同一个文件,我尝试了这段代码,但我不知道它的问题在哪里

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

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

    model->appendRow(fields);

}

请帮忙吗?

1 个答案:

答案 0 :(得分:88)

您必须替换字符串行

QString line = in.readLine();

进入

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