从 QML url 获取路径 [英] Get the path from a QML url

查看:14
本文介绍了从 QML url 获取路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FileDialog 给出一个 QML url 变量.theurl.toString() 给出类似 file:///c:fooar.txt 的内容.如何获取 c:fooar.txt?

FileDialog gives a QML url variable. theurl.toString() gives something like file:///c:fooar.txt. How do I get c:fooar.txt?

我想以跨平台的方式进行,理想情况下不依赖于正则表达式风格的黑客.QUrl 提供了一个 path() 方法,但我似乎无法从 QML 访问它.

I want to do it in a cross-platform way, and ideally without relying on regex-style hacks. QUrl provides a path() method, but I don't seem to be able to access it from QML.

推荐答案

正如评论中已经指出的那样,似乎没有办法(还没有?)在没有正则表达式的情况下获取路径本身.所以这是唯一的方法:

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

这个正则表达式应该非常健壮,因为它只从字符串的开头删除 file:///.

This regex should be quite robust as it only removes the file:/// from the beginning of the string.

您还需要取消转义一些 HTML 字符(如果文件名包含例如散列 #,这将返回为 %23.我们使用JavaScript 函数 decodeURIComponent()).

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

如果你不仅要过滤 file:/// 还要过滤 qrc://http://,你可以使用这个正则表达式:

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

所以新的、完整的代码是:

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

这是 RegEx 的一个很好的游乐场:http://regex101.com/r/zC1nD5/1

This is a good playground for RegEx'es: http://regex101.com/r/zC1nD5/1

这篇关于从 QML url 获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆