url QML Basic Type

The url type refers to a resource locator (like a file name, for example). It can be either absolute, e.g. "http://qt-project.org", or relative, e.g. "pics/logo.png". A relative URL is resolved relative to the URL of the containing component.

For example, the following assigns a valid URL to the Image::source property, which is of type url:

Image { source: "pics/logo.png" }

When integrating with C++, note that any QUrl value passed into QML from C++ is automatically converted into a url value, and vice-versa.

Using the url Type

When a relative URL is written to a url type property, it is converted into a URL object, so matching the URL value against the input string value will fail. Instead, convert the string to a URL using Qt.resolvedUrl() for means of comparison, and use toString() to get the contents of the URL:

Image {
    source: "pics/logo.png"

    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 == "pics/logo.png")

        // This prints 'true' as Qt.resovledUrl() converts the string into a
        // URL with the correctly resolved path
        console.log(source == Qt.resolvedUrl("pics/logo.png"))

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

Note: When referring to files stored with the Qt Resource System from within QML, you should use "qrc:///" instead of ":/" as QML requires URL paths. Relative URLs resolved from within that file will use the same protocol.

Additionally, URLs may contain encoded characters using the 'percent-encoding' scheme specified by RFC 3986. These characters will be preserved within properties of type url, to allow QML code to construct precise URL values. An exception to this rule is the preemptive decoding of directory-separator characters ('/') - these characters are decoded to allow the URL to be correctly classified.

For example, a local file containing a '#' character, which would normally be interpreted as the beginning of the URL 'fragment' element, can be accessed by encoding the characters of the file name:

Image { source: encodeURIComponent("/tmp/test#1.png") }

This basic type is provided by the QML language.

See also QML Basic Types.

© The Qt Company Ltd
Licensed under the GNU Free Documentation License, Version 1.3.
https://doc.qt.io/qt-5.14/qml-url.html