从QML网址获取路径

Tim*_*mmm 14 url qt filedialog qml

FileDialog给出一个QML url变量.theurl.toString()给出类似的东西file:///c:\foo\bar.txt.我怎么得到c:\foo\bar.txt

我想以跨平台的方式做到这一点,理想情况下不依赖于正则表达式的黑客攻击.QUrl提供了一种path()方法,但我似乎无法从QML访问它.

Ant*_*ard 6

按照上面 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)


moz*_*ozz 5

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:

Basic solution

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()).

Fully featured example

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

  • 我的意思是,它不适用于其他方案,例如`qrc://`或`http://`。我并不是说在许多情况下都行不通;只是指出它与`QUrl :: path()`不同。 (5认同)

Ton*_*ony 5

在 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)