Tim*_*mmm 14 url qt filedialog qml
FileDialog
给出一个QML url
变量.theurl.toString()
给出类似的东西file:///c:\foo\bar.txt
.我怎么得到c:\foo\bar.txt
?
我想以跨平台的方式做到这一点,理想情况下不依赖于正则表达式的黑客攻击.QUrl
提供了一种path()
方法,但我似乎无法从QML访问它.
按照上面 Chris Dolan 的回答,使用 C++ 中的插槽来处理这个问题可能是最好的:
public slots:
void handleFileChosen(const QString &urlString) {
const QUrl url(urlString);
if (url.isLocalFile()) {
setFile(QDir::toNativeSeparators(url.toLocalFile()));
} else {
setFile(urlString);
}
}
Run Code Online (Sandbox Code Playgroud)
As noted in the comments already, there seems to be no way (yet?) to get the path itself without a regex. So this is the only way to go:
FileDialog {
onAccepted: {
var path = myFileDialog.fileUrl.toString();
// remove prefixed "file:///"
path = path.replace(/^(file:\/{3})/,"");
// unescape html codes like '%23' for '#'
cleanPath = decodeURIComponent(path);
console.log(cleanPath)
}
}
Run Code Online (Sandbox Code Playgroud)
This regex should be quite robust as it only removes the file:///
from the beginning of the string.
You will also need to unescape some HTML characters (if the file name contains e.g. the hash #
, this would be returned as %23
. We decode this by using the JavaScript function decodeURIComponent()
).
If you not only want to filter the file:///
but also qrc://
and http://
, you can use this RegEx:
^(file:\/{3})|(qrc:\/{2})|(http:\/{2})
Run Code Online (Sandbox Code Playgroud)
So the new, complete code would be:
FileDialog {
onAccepted: {
var path = myFileDialog.fileUrl.toString();
// remove prefixed "file:///"
path= path.replace(/^(file:\/{3})|(qrc:\/{2})|(http:\/{2})/,"");
// unescape html codes like '%23' for '#'
cleanPath = decodeURIComponent(path);
console.log(cleanPath)
}
}
Run Code Online (Sandbox Code Playgroud)
This is a good playground for RegEx'es: http://regex101.com/r/zC1nD5/1
在 MS Windows 中,“file:///c:\foo\bar.txt”应转换为“c:\foo\bar.txt”。然而,在 Linux 中,url“file:///Users/data/abcdef”的正确路径为“/Users/data/abcdef”。我创建了一个简单的函数来将 url 转换为路径:
function urlToPath(urlString) {
var s
if (urlString.startsWith("file:///")) {
var k = urlString.charAt(9) === ':' ? 8 : 7
s = urlString.substring(k)
} else {
s = urlString
}
return decodeURIComponent(s);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14387 次 |
最近记录: |