Qt:读取 .txt 文件时遇到问题

Qt: having problems with reading a .txt file

几天前我开始使用Qt。然而,当我想读取一个文件时,尽管文件是打开的,但我无法从中获取一行。 qDebug 的输出是 "The file is open",但是 while 什么都不做(我的 TextArea(文本编辑)中没有得到 "Does it work?" 文本)。 我错过了什么?文件肯定在,可以打开,有2行。

    QFile file("savefile.txt");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"The file is not open.";
        return;
    }
    else
    {
        qDebug()<<"The file is open.";
        QString line;
        QTextStream in(&file);
        while(!in.atEnd())
        {
            line = in.readLine();
            qDebug()<<"Line: "<<line.toLatin1();
            ui->TextArea->setText("Does it work?");
        }
        file.close();
    }

那么,我错过了什么? 我尝试根据 Qt 入门教程执行此操作,但没有创建对话框(Link to the page,向下滚动到 "Opening files")。 提前感谢您的帮助!

编辑 1: 由于文件有 2 行(正好是 "Asd." 和 "asd."),我用 for(int i = 0; i<2; i++). QDebug 现在告诉我两次:

Line:  ""
Line:  ""

我假设 while(!in.atEnd()) 有问题。

EDIT2: 将循环和 in.readLine() 替换为 ui->TextArea->setText(in.readAll().toLatin1());。结果仍然相同(如果我使用 ui->TextArea->setText("Hey!");,它会起作用。

问题已通过以下方式解决:

1.重新安装 Qt.

我用Qt Maintenance工具从我的电脑上删除了软件,然后重新下载了。可能有些文件丢失了。

2。文件打不开的可能原因:文件夹错误

由于我将我的项目命名为 RPG(项目文件为 RPG.pro),我将文件放入文件夹 RPG 而不是放入同一目录中的其他文件夹,build_RPG_desktop[ ...],其中包含 ui_mainwindow 头文件(我没有更改主窗口的默认名称)。 build_RPG[...] 文件夹中的文件 "Data.txt" 在使用以下代码重新安装 Qt 后可以成功读取:

QString fileName = "Data.txt";
if (!fileName.isEmpty())
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"Error. File not found";
        return;
    }
    QTextStream in(&file);
    ui->TextArea->setText(in.readAll());
    file.close();
}

注意:我修改了 TextEdit 字段并将其名称设置为 TextArea。 ui->TextArea->setText() 设置文本编辑字段的内容。