Qt reading from QTextStream

Qt reading from QTextStream

本文关键字:QTextStream from reading Qt      更新时间:2023-10-16

我正在尝试读取一个文本文件,并在QPlainTextEdit中显示内容。请你指出我做错了什么:

QFile jsonFile("data.json");  
if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug() << "Failed to open file";
    qDebug() << jsonFile.errorString();
    return;
}
else
{
    qDebug() << "File opened";
} //It returns that the file opened successfully
qDebug() << "File Exists?: " << jsonFile.exists(); //Yep, it exists.
QTextStream outStream(&jsonFile);
QString textString = outStream.readAll();
qDebug() << "Text string: " << textString; //textString is empty! ""
ui->fileToPost->setPlainText(textString); //fileToPost is the QPlainTextEdit
jsonFile.close();

如果我做一些类似的事情

QString textString = "The cat sat on the mat";

它显示良好。问题是没有从流(或者文件)中读取任何内容。

试着检查文件的绝对路径,可能不是您期望的位置:qDebug()<<QFileInfo("data.json").absoluteFilePath();