浅析QML语言中的Qt.resolvedUrl

我看过很多的Qt代码,里面有时会用到Qt.resolvedUrl.有时候不仔细想,还真是一知半解.看了Qt的文档

url resolvedUrl(url url)

Returns url resolved relative to the URL of the caller.

你可能还会是一头雾水.这样吧,我们还是利用一个简单的例程来说们问题:


        Image {
            anchors.fill: parent
            source: "images/girl.jpg"

            Component.onCompleted: {
                // This prints 'false'. Although "pics/logo.png" was the input string,
                // it's been converted from a string to a URL, so these two are not the same.
                console.log(source == "images/girl.jpg")

                // This prints 'true' as Qt.resovledUrl() converts the string into a
                // URL with the correctly resolved path
                console.log("resolvedurl: " + Qt.resolvedUrl("images/girl.jpg"))
                console.log(source == Qt.resolvedUrl("images/girl.jpg"))

                // This prints the absolute path, e.g. "file:///path/to/pics/logo.png"
                console.log(source.toString())
            }
        }

上面的例程中,我们在Image中显示另一个女孩的照片.从代码中可以看出来,它明显使用的是相对路径.虽然我们输入的是相对路径,当它被输入到一个url的类型的属性时(比如 Image中的source),它将被转换为一个QUrl的对象.如果我们直接把url中的内容和我们输入的内容相比较的话,就会失败.比如上面的代码的输出结果是:




Starting /usr/ubuntu-sdk-dev/bin/qmlscene...
qml: false
qml: resolvedurl: file:///home/liuxg/qml/resolveurl/images/girl.jpg
qml: true
qml: file:///home/liuxg/qml/resolveurl/images/girl.jpg

从上面的代码中可以看出来,使用Qt.resolvedUrl可以把我们的相对路径的url转换为绝对路径的path.

整个项目的源码在:https://github.com/liu-xiao-guo/resolveurl




                
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值