【发布时间】:2017-11-07 00:33:47
【问题描述】:
所以我试图通过执行以下操作将 QFile 转换为 QString:
void MainWindow::openTemplateFile(QString location)
{
if (location.isEmpty())
return;
else
{
QString variable;
templateFile.setFileName(location);
if (!templateFile.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::information(this, "Unable to open template",
templateFile.errorString());
return;
}
else // file opened and ready to read from
{
QTextStream in(&templateFile);
QString fileText = in.readAll();
qDebug() << templateFile.size() << in.readAll();
}
}
}
但是,我在调试控制台中得到以下结果:
48 ""
templateFile 确实存在并且是 MainWindow 类的一部分。这也是简化的代码 - 在实际程序中,我从文件中读取字符并且它可以正常工作。位置字符串是 QFileDialog::getOpenFileName 函数的结果,我用它打开一个 txt 文件。
【问题讨论】:
-
两个cmets:(1)
readAll()方法没有办法报错,(2)方法返回一个QByteArray(不是QString),那个QString构造函数将在数组中的第一个“0”处停止。如果有字节为“0”,则字符串会更短。 -
@bnaecker 那么如何有效地将 QFile 的内容读取到 QString 中?
-
@bnaecker OP 调用
QTextStream::readAll(),而不是QFile::readAll()。前者也返回QString