浅析QML语言中的Qt.resolvedUrl

517 阅读1分钟

我看过很多的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.

整个项目的源码在:github.com/liu-xiao-gu…

\

\