Chi*_*Huu 1 c++ file-io qt qml qtquick2
我正在使用 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();
}
Run Code Online (Sandbox Code Playgroud)
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 {};
}
}
Run Code Online (Sandbox Code Playgroud)
*.qml
var text = helper.readFile(fileDialog.fileUrl)
console.log(text)
Run Code Online (Sandbox Code Playgroud)