【问题标题】:Qt - Why unable read file using QFile with directory which get from FileDialog?Qt - 为什么无法使用从 FileDialog 获取的目录使用 QFile 读取文件?
【发布时间】:2019-04-02 00:17:26
【问题描述】:
我正在使用 QFile 在 Qt 5.12 上读取文件。我尝试从我的计算机中读取一个文件,但是当我使用从 FileDialog 读取的目录具有“file:///”前缀时。谁能告诉我为什么会出错以及如何使用从 FileDialog 获取的 URL?
谢谢!
QFile file("C:/Users/HuuChinhPC/Desktop/my_txt.txt"); // this work
//QFile file("file:///C:/Users/HuuChinhPC/Desktop/my_txt.txt"); //didn't work
QString fileContent;
if (file.open(QIODevice::ReadOnly) ) {
QString line;
QTextStream t( &file );
do {
line = t.readLine();
fileContent += line;
} while (!line.isNull());
file.close();
} else {
emit error("Unable to open the file");
return QString();
}
【问题讨论】:
标签:
c++
qt
file-io
qml
qtquick2
【解决方案1】:
FileDialog 返回一个 url,因为在 QML 中使用了该类型的数据,但 QFile 不是,因此您必须将 QUrl 转换为使用的字符串 toLocalFile():
Q_INVOKABLE QString readFile(const QUrl & url){
if(!url.isLocalFile()){
Q_EMIT error("It is not a local file");
return {};
}
QFile file(url.toLocalFile());
QString fileContent;
if (file.open(QIODevice::ReadOnly) ) {
QString line;
QTextStream t( &file );
do {
line = t.readLine();
fileContent += line;
} while (!line.isNull());
file.close();
return fileContent;
} else {
Q_EMIT error("Unable to open the file");
return {};
}
}
*.qml
var text = helper.readFile(fileDialog.fileUrl)
console.log(text)
【解决方案2】:
您必须去除文件前缀才能使用从 FileDialog 获取的 URL:
QFile file("file:///C:/Users/HuuChinhPC/Desktop/my_txt.txt")
if (Qt.platform.os === "windows") {
return file.replace(/^(file:\/{3})|(file:)|(qrc:\/{3})|(http:\/{3})/,"")
}
else {
return file.replace(/^(file:\/{2})|(qrc:\/{2})|(http:\/{2})/,"");
}