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

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

问题描述

FileDialog给出QML url变量. theurl.toString()给出类似file:///c:\foo\bar.txt的内容.如何获得c:\foo\bar.txt?

FileDialog gives a QML url variable. theurl.toString() gives something like file:///c:\foo\bar.txt. How do I get c:\foo\bar.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://,则可以使用此RegEx:

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网址获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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