![]() |
Qt 6.x
The Qt SDK
|
\inmodule QtCore More...
#include <qurl.h>
Public Types | |
enum | ParsingMode { TolerantMode , StrictMode , DecodedMode } |
The parsing mode controls the way QUrl parses strings. More... | |
enum | UrlFormattingOption : unsigned int { None = 0x0 , RemoveScheme = 0x1 , RemovePassword = 0x2 , RemoveUserInfo = RemovePassword | 0x4 , RemovePort = 0x8 , RemoveAuthority = RemoveUserInfo | RemovePort | 0x10 , RemovePath = 0x20 , RemoveQuery = 0x40 , RemoveFragment = 0x80 , PreferLocalFile = 0x200 , StripTrailingSlash = 0x400 , RemoveFilename = 0x800 , NormalizePathSegments = 0x1000 } |
The formatting options define how the URL is formatted when written out as text. More... | |
enum | ComponentFormattingOption : unsigned int { PrettyDecoded = 0x000000 , EncodeSpaces = 0x100000 , EncodeUnicode = 0x200000 , EncodeDelimiters = 0x400000 | 0x800000 , EncodeReserved = 0x1000000 , DecodeReserved = 0x2000000 , FullyEncoded = EncodeSpaces | EncodeUnicode | EncodeDelimiters | EncodeReserved , FullyDecoded = FullyEncoded | DecodeReserved | 0x4000000 } |
enum | UserInputResolutionOption { DefaultResolution , AssumeLocalFile } |
enum | AceProcessingOption : unsigned int { IgnoreIDNWhitelist = 0x1 , AceTransitionalProcessing = 0x2 } |
typedef QUrlTwoFlags< UrlFormattingOption, ComponentFormattingOption > | FormattingOptions |
typedef QUrlPrivate * | DataPtr |
Public Member Functions | |
QUrl () | |
Constructs an empty QUrl object. | |
QUrl (const QUrl ©) noexcept | |
Constructs a copy of other. | |
QUrl & | operator= (const QUrl ©) noexcept |
Assigns the specified url to this object. | |
QUrl (const QString &url, ParsingMode mode=TolerantMode) | |
\macro QT_NO_URL_CAST_FROM_STRING | |
QUrl & | operator= (const QString &url) |
Assigns the specified url to this object. | |
QUrl (QUrl &&other) noexcept | |
Move-constructs a QUrl instance, making it point at the same object that other was pointing to. | |
~QUrl () | |
Destructor; called immediately before the object is deleted. | |
void | swap (QUrl &other) noexcept |
void | setUrl (const QString &url, ParsingMode mode=TolerantMode) |
Parses url and sets this object to that value. | |
QString | url (FormattingOptions options=FormattingOptions(PrettyDecoded)) const |
Returns a string representation of the URL. | |
QString | toString (FormattingOptions options=FormattingOptions(PrettyDecoded)) const |
Returns a string representation of the URL. | |
QString | toDisplayString (FormattingOptions options=FormattingOptions(PrettyDecoded)) const |
QUrl | adjusted (FormattingOptions options) const |
QByteArray | toEncoded (FormattingOptions options=FullyEncoded) const |
Returns the encoded representation of the URL if it's valid; otherwise an empty QByteArray is returned. | |
bool | isValid () const |
Returns true if the URL is non-empty and valid; otherwise returns false . | |
QString | errorString () const |
bool | isEmpty () const |
Returns true if the URL has no data; otherwise returns false . | |
void | clear () |
Resets the content of the QUrl. | |
void | setScheme (const QString &scheme) |
Sets the scheme of the URL to scheme. | |
QString | scheme () const |
Returns the scheme of the URL. | |
void | setAuthority (const QString &authority, ParsingMode mode=TolerantMode) |
Sets the authority of the URL to authority. | |
QString | authority (ComponentFormattingOptions options=PrettyDecoded) const |
Returns the authority of the URL if it is defined; otherwise an empty string is returned. | |
void | setUserInfo (const QString &userInfo, ParsingMode mode=TolerantMode) |
Sets the user info of the URL to userInfo. | |
QString | userInfo (ComponentFormattingOptions options=PrettyDecoded) const |
Returns the user info of the URL, or an empty string if the user info is undefined. | |
void | setUserName (const QString &userName, ParsingMode mode=DecodedMode) |
Sets the URL's user name to userName. | |
QString | userName (ComponentFormattingOptions options=FullyDecoded) const |
Returns the user name of the URL if it is defined; otherwise an empty string is returned. | |
void | setPassword (const QString &password, ParsingMode mode=DecodedMode) |
Sets the URL's password to password. | |
QString | password (ComponentFormattingOptions=FullyDecoded) const |
Returns the password of the URL if it is defined; otherwise an empty string is returned. | |
void | setHost (const QString &host, ParsingMode mode=DecodedMode) |
Sets the host of the URL to host. | |
QString | host (ComponentFormattingOptions=FullyDecoded) const |
Returns the host of the URL if it is defined; otherwise an empty string is returned. | |
void | setPort (int port) |
Sets the port of the URL to port. | |
int | port (int defaultPort=-1) const |
void | setPath (const QString &path, ParsingMode mode=DecodedMode) |
Sets the path of the URL to path. | |
QString | path (ComponentFormattingOptions options=FullyDecoded) const |
Returns the path of the URL. | |
QString | fileName (ComponentFormattingOptions options=FullyDecoded) const |
bool | hasQuery () const |
void | setQuery (const QString &query, ParsingMode mode=TolerantMode) |
Sets the query string of the URL to query. | |
void | setQuery (const QUrlQuery &query) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
QString | query (ComponentFormattingOptions=PrettyDecoded) const |
Returns the query string of the URL if there's a query string, or an empty result if not. | |
bool | hasFragment () const |
QString | fragment (ComponentFormattingOptions options=PrettyDecoded) const |
Returns the fragment of the URL. | |
void | setFragment (const QString &fragment, ParsingMode mode=TolerantMode) |
Sets the fragment of the URL to fragment. | |
QUrl | resolved (const QUrl &relative) const |
Returns the result of the merge of this URL with relative. | |
bool | isRelative () const |
Returns true if the URL is relative; otherwise returns false . | |
bool | isParentOf (const QUrl &url) const |
Returns true if this URL is a parent of childUrl. | |
bool | isLocalFile () const |
QString | toLocalFile () const |
Returns the path of this URL formatted as a local file path. | |
void | detach () |
bool | isDetached () const |
bool | operator< (const QUrl &url) const |
bool | operator== (const QUrl &url) const |
Returns true if this URL and the given url are equal; otherwise returns false . | |
bool | operator!= (const QUrl &url) const |
Returns true if this URL and the given url are not equal; otherwise returns false . | |
bool | matches (const QUrl &url, FormattingOptions options) const |
DataPtr & | data_ptr () |
Static Public Member Functions | |
static QUrl | fromEncoded (QByteArrayView input, ParsingMode mode=TolerantMode) |
Parses input and returns the corresponding QUrl. | |
static QUrl | fromUserInput (const QString &userInput, const QString &workingDirectory=QString(), UserInputResolutionOptions options=DefaultResolution) |
Returns a valid URL from a user supplied userInput string if one can be deduced. | |
static QUrl | fromLocalFile (const QString &localfile) |
Returns a QUrl representation of localFile, interpreted as a local file. | |
static QString | fromPercentEncoding (const QByteArray &) |
Returns a decoded copy of input. | |
static QByteArray | toPercentEncoding (const QString &, const QByteArray &exclude=QByteArray(), const QByteArray &include=QByteArray()) |
Returns an encoded copy of input. | |
static QString | fromAce (const QByteArray &domain, AceProcessingOptions options={}) |
static QByteArray | toAce (const QString &domain, AceProcessingOptions options={}) |
static QStringList | idnWhitelist () |
static QStringList | toStringList (const QList< QUrl > &uris, FormattingOptions options=FormattingOptions(PrettyDecoded)) |
static QList< QUrl > | fromStringList (const QStringList &uris, ParsingMode mode=TolerantMode) |
static void | setIdnWhitelist (const QStringList &) |
Friends | |
class | QUrlQuery |
Q_CORE_EXPORT size_t | qHash (const QUrl &url, size_t seed) noexcept |
Related Symbols | |
(Note that these are not member symbols.) | |
QUrl (const QString &url, ParsingMode parsingMode) | |
\macro QT_NO_URL_CAST_FROM_STRING | |
QDataStream & | operator<< (QDataStream &out, const QUrl &url) |
Writes url url to the stream out and returns a reference to the stream. | |
QDataStream & | operator>> (QDataStream &in, QUrl &url) |
Reads a url into url from the stream in and returns a reference to the stream. | |
\inmodule QtCore
The QUrl class provides a convenient interface for working with URLs.
\reentrant
It can parse and construct URLs in both encoded and unencoded form. QUrl also has support for internationalized domain names (IDNs).
The most common way to use QUrl is to initialize it via the constructor by passing a QString containing a full URL. QUrl objects can also be created from a QByteArray containing a full URL using QUrl::fromEncoded(), or heuristically from incomplete URLs using QUrl::fromUserInput(). The URL representation can be obtained from a QUrl using either QUrl::toString() or QUrl::toEncoded().
URLs can be represented in two forms: encoded or unencoded. The unencoded representation is suitable for showing to users, but the encoded representation is typically what you would send to a web server. For example, the unencoded URL "http://bühler.example.com/List of applicants.xml" would be sent to the server as "http://xn--bhler-kva.example.com/List%20of%20applicants.xml".
A URL can also be constructed piece by piece by calling setScheme(), setUserName(), setPassword(), setHost(), setPort(), setPath(), setQuery() and setFragment(). Some convenience functions are also available: setAuthority() sets the user name, password, host and port. setUserInfo() sets the user name and password at once.
Call isValid() to check if the URL is valid. This can be done at any point during the constructing of a URL. If isValid() returns false
, you should clear() the URL before proceeding, or start over by parsing a new URL with setUrl().
Constructing a query is particularly convenient through the use of the \l QUrlQuery class and its methods QUrlQuery::setQueryItems(), QUrlQuery::addQueryItem() and QUrlQuery::removeQueryItem(). Use QUrlQuery::setQueryDelimiters() to customize the delimiters used for generating the query string.
For the convenience of generating encoded URL strings or query strings, there are two static functions called fromPercentEncoding() and toPercentEncoding() which deal with percent encoding and decoding of QString objects.
fromLocalFile() constructs a QUrl by parsing a local file path. toLocalFile() converts a URL to a local file path.
The human readable representation of the URL is fetched with toString(). This representation is appropriate for displaying a URL to a user in unencoded form. The encoded form however, as returned by toEncoded(), is for internal use, passing to web servers, mail clients and so on. Both forms are technically correct and represent the same URL unambiguously – in fact, passing either form to QUrl's constructor or to setUrl() will yield the same QUrl object.
QUrl conforms to the URI specification from \l{RFC 3986} (Uniform Resource Identifier: Generic Syntax), and includes scheme extensions from \l{RFC 1738} (Uniform Resource Locators). Case folding rules in QUrl conform to \l{RFC 3491} (Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)). It is also compatible with the \l{http://freedesktop.org/wiki/Specifications/file-uri-spec/}{file URI specification} from freedesktop.org, provided that the locale encodes file names using UTF-8 (required by IDN).
enum QUrl::AceProcessingOption : unsigned int |
The ACE processing options control the way URLs are transformed to and from ASCII-Compatible Encoding.
\value IgnoreIDNWhitelist Ignore the IDN whitelist when converting URLs to Unicode. \value AceTransitionalProcessing Use transitional processing described in UTS #46. This allows better compatibility with IDNA 2003 specification.
The default is to use nontransitional processing and to allow non-ASCII characters only inside URLs whose top-level domains are listed in the IDN whitelist.
Enumerator | |
---|---|
IgnoreIDNWhitelist | |
AceTransitionalProcessing |
enum QUrl::ComponentFormattingOption : unsigned int |
The component formatting options define how the components of an URL will be formatted when written out as text. They can be combined with the options from QUrl::FormattingOptions when used in toString() and toEncoded().
\value PrettyDecoded The component is returned in a "pretty form", with most percent-encoded characters decoded. The exact behavior of PrettyDecoded varies from component to component and may also change from Qt release to Qt release. This is the default.
\value EncodeSpaces Leave space characters in their encoded form ("%20").
\value EncodeUnicode Leave non-US-ASCII characters encoded in their UTF-8 percent-encoded form (e.g., "%C3%A9" for the U+00E9 codepoint, LATIN SMALL LETTER E WITH ACUTE).
\value EncodeDelimiters Leave certain delimiters in their encoded form, as would appear in the URL when the full URL is represented as text. The delimiters are affected by this option change from component to component. This flag has no effect in toString() or toEncoded().
\value EncodeReserved Leave US-ASCII characters not permitted in the URL by the specification in their encoded form. This is the default on toString() and toEncoded().
\value DecodeReserved Decode the US-ASCII characters that the URL specification does not allow to appear in the URL. This is the default on the getters of individual components.
\value FullyEncoded Leave all characters in their properly-encoded form, as this component would appear as part of a URL. When used with toString(), this produces a fully-compliant URL in QString form, exactly equal to the result of toEncoded()
\value FullyDecoded Attempt to decode as much as possible. For individual components of the URL, this decodes every percent encoding sequence, including control characters (U+0000 to U+001F) and UTF-8 sequences found in percent-encoded form. Use of this mode may cause data loss, see below for more information.
The values of EncodeReserved and DecodeReserved should not be used together in one call. The behavior is undefined if that happens. They are provided as separate values because the behavior of the "pretty mode" with regards to reserved characters is different on certain components and specially on the full URL.
Enumerator | |
---|---|
PrettyDecoded | |
EncodeSpaces | |
EncodeUnicode | |
EncodeDelimiters | |
EncodeReserved | |
DecodeReserved | |
FullyEncoded | |
FullyDecoded |
enum QUrl::ParsingMode |
The parsing mode controls the way QUrl parses strings.
\value TolerantMode QUrl will try to correct some common errors in URLs. This mode is useful for parsing URLs coming from sources not known to be strictly standards-conforming.
\value StrictMode Only valid URLs are accepted. This mode is useful for general URL validation.
\value DecodedMode QUrl will interpret the URL component in the fully-decoded form, where percent characters stand for themselves, not as the beginning of a percent-encoded sequence. This mode is only valid for the setters setting components of a URL; it is not permitted in the QUrl constructor, in fromEncoded() or in setUrl(). For more information on this mode, see the documentation for \l {QUrl::ComponentFormattingOption}{QUrl::FullyDecoded}.
In TolerantMode, the parser has the following behaviour:
\list
\endlist
When in StrictMode, if a parsing error is found, isValid() will return false
and errorString() will return a message describing the error. If more than one error is detected, it is undefined which error gets reported.
Note that TolerantMode is not usually enough for parsing user input, which often contains more errors and expectations than the parser can deal with. When dealing with data coming directly from the user – as opposed to data coming from data-transfer sources, such as other programs – it is recommended to use fromUserInput().
Enumerator | |
---|---|
TolerantMode | |
StrictMode | |
DecodedMode |
enum QUrl::UrlFormattingOption : unsigned int |
The formatting options define how the URL is formatted when written out as text.
\value None The format of the URL is unchanged. \value RemoveScheme The scheme is removed from the URL. \value RemovePassword Any password in the URL is removed. \value RemoveUserInfo Any user information in the URL is removed. \value RemovePort Any specified port is removed from the URL. \value RemoveAuthority \value RemovePath The URL's path is removed, leaving only the scheme, host address, and port (if present). \value RemoveQuery The query part of the URL (following a '?' character) is removed. \value RemoveFragment \value RemoveFilename The filename (i.e. everything after the last '/' in the path) is removed. The trailing '/' is kept, unless StripTrailingSlash is set. Only valid if RemovePath is not set. \value PreferLocalFile If the URL is a local file according to isLocalFile() and contains no query or fragment, a local file path is returned. \value StripTrailingSlash The trailing slash is removed from the path, if one is present. \value NormalizePathSegments Modifies the path to remove redundant directory separators, and to resolve "."s and ".."s (as far as possible). For non-local paths, adjacent slashes are preserved.
Note that the case folding rules in \l{RFC 3491}{Nameprep}, which QUrl conforms to, require host names to always be converted to lower case, regardless of the Qt::FormattingOptions used.
The options from QUrl::ComponentFormattingOptions are also possible.
Enumerator | |
---|---|
None | |
RemoveScheme | |
RemovePassword | |
RemoveUserInfo | |
RemovePort | |
RemoveAuthority | |
RemovePath | |
RemoveQuery | |
RemoveFragment | |
PreferLocalFile | |
StripTrailingSlash | |
RemoveFilename | |
NormalizePathSegments |
The user input resolution options define how fromUserInput() should interpret strings that could either be a relative path or the short form of a HTTP URL. For instance {file.pl} can be either a local file or the URL
{http://file.pl}.
\value DefaultResolution The default resolution mechanism is to check whether a local file exists, in the working directory given to fromUserInput, and only return a local path in that case. Otherwise a URL is assumed. \value AssumeLocalFile This option makes fromUserInput() always return a local path unless the input contains a scheme, such as {http://file.pl}. This is useful for applications such as text editors, which are able to create the file if it doesn't exist.
Enumerator | |
---|---|
DefaultResolution | |
AssumeLocalFile |
QUrl::QUrl | ( | ) |
Constructs an empty QUrl object.
Definition at line 1843 of file qurl.cpp.
Referenced by adjusted(), fromEncoded(), and fromUserInput().
|
noexcept |
QUrl | ( | const QString & | url, |
ParsingMode | parsingMode = TolerantMode |
||
) |
\macro QT_NO_URL_CAST_FROM_STRING
Disables automatic conversions from QString (or char *) to QUrl.
Compiling your code with this define is useful when you have a lot of code that uses QString for file names and you wish to convert it to use QUrl for network transparency. In any code that uses QUrl, it can help avoid missing QUrl::resolved() calls, and other misuses of QString to QUrl conversions.
For example, if you have code like
you can rewrite it as
Constructs a URL by parsing url. Note this constructor expects a proper URL or URL-Reference and will not attempt to guess intent. For example, the following declaration:
Will construct a valid URL but it may not be what one expects, as the scheme() part of the input is missing. For a string like the above, applications may want to use fromUserInput(). For this constructor or setUrl(), the following is probably what was intended:
QUrl will automatically percent encode all characters that are not allowed in a URL and decode the percent-encoded sequences that represent an unreserved character (letters, digits, hyphens, underscores, dots and tildes). All other characters are left in their original forms.
Parses the url using the parser mode parsingMode. In TolerantMode (the default), QUrl will correct certain mistakes, notably the presence of a percent character ('') not followed by two hexadecimal digits, and it will accept any character in any position. In StrictMode, encoding mistakes will not be tolerated and QUrl will also check that certain forbidden characters are not present in unencoded form. If an error is detected in StrictMode, isValid() will return false. The parsing mode DecodedMode is not permitted in this context.
Example:
To construct a URL from an encoded string, you can also use fromEncoded():
Both functions are equivalent and, in Qt 5, both functions accept encoded data. Usually, the choice of the QUrl constructor or setUrl() versus fromEncoded() will depend on the source data: the constructor and setUrl() take a QString, whereas fromEncoded takes a QByteArray.
Definition at line 1835 of file qurl.cpp.
|
inlinenoexcept |
QUrl::~QUrl | ( | ) |
Destructor; called immediately before the object is deleted.
Definition at line 1859 of file qurl.cpp.
References QBasicAtomicInteger< T >::deref(), and QUrlPrivate::ref.
Referenced by toString().
QUrl QUrl::adjusted | ( | QUrl::FormattingOptions | options | ) | const |
Returns an adjusted version of the URL. The output can be customized by passing flags with options.
The encoding options from QUrl::ComponentFormattingOption don't make much sense for this method, nor does QUrl::PreferLocalFile.
This is always equivalent to QUrl(url.toString(options)).
Definition at line 2921 of file qurl.cpp.
References QUrl(), QUrlPrivate::appendPath(), detach(), FullyEncoded, isValid(), NormalizePathSegments, QUrlPrivate::Path, RemoveAuthority, RemoveFilename, RemoveFragment, RemovePassword, RemovePath, RemovePort, RemoveQuery, RemoveScheme, RemoveUserInfo, setAuthority(), setFragment(), setPassword(), setPath(), QUrlPrivate::setPath(), setPort(), setQuery(), setScheme(), setUserInfo(), and StripTrailingSlash.
Referenced by QWindowsXpNativeFileDialog::doExec(), QQuickTextControlPrivate::setContent(), and QTextBrowserPrivate::setSource().
QString QUrl::authority | ( | ComponentFormattingOptions | options = PrettyDecoded | ) | const |
Returns the authority of the URL if it is defined; otherwise an empty string is returned.
This function returns an unambiguous value, which may contain that characters still percent-encoded, plus some control sequences not representable in decoded form in QString.
The options argument controls how to format the user info component. The value of QUrl::FullyDecoded is not permitted in this function. If you need to obtain fully decoded data, call userName(), password(), host() and port() individually.
Definition at line 2052 of file qurl.cpp.
References QUrlPrivate::appendAuthority(), QUrlPrivate::Authority, FullyDecoded, and qWarning.
Referenced by QNetworkAccessFileBackendFactory::create(), QQmlFile::isLocalFile(), isParentOf(), setAuthority(), and QQmlFile::urlToLocalFileOrQrc().
void QUrl::clear | ( | ) |
Resets the content of the QUrl.
After calling this function, the QUrl is equal to one that has been constructed with the default empty constructor.
Definition at line 1901 of file qurl.cpp.
References QBasicAtomicInteger< T >::deref(), and QUrlPrivate::ref.
Referenced by operator=(), QQuickIcon::resetSource(), QQuickIcon::setSource(), QAndroidAudioDecoder::setSourceDevice(), AVFAudioDecoder::setSourceDevice(), QFFmpegAudioDecoder::setSourceDevice(), QGstreamerAudioDecoder::setSourceDevice(), MFAudioDecoderControl::setSourceDevice(), and QGtk3FileDialogHelper::show().
void QUrl::detach | ( | ) |
Forces a detach.
Definition at line 3287 of file qurl.cpp.
References qAtomicDetach().
Referenced by adjusted(), fromLocalFile(), operator=(), resolved(), setAuthority(), setFragment(), setHost(), setPassword(), setPath(), setPort(), setQuery(), setQuery(), setScheme(), setUrl(), setUserInfo(), and setUserName().
QString QUrl::errorString | ( | ) | const |
Returns an error message if the last operation that modified this QUrl object ran into a parsing error. If no error was detected, this function returns an empty string and isValid() returns true
.
The error message returned by this function is technical in nature and may not be understood by end users. It is mostly useful to developers trying to understand why QUrl will not accept some input.
Definition at line 3590 of file qurl.cpp.
References appendComponentIfPresent(), QString::chop(), QString::endsWith(), errorMessage(), QUrlPrivate::Fragment, QUrlPrivate::fragment, QUrlPrivate::Host, QUrlPrivate::host, QString::isEmpty(), QUrlPrivate::NoError, QString::number(), QUrlPrivate::path, QUrlPrivate::port, QUrlPrivate::Query, QUrlPrivate::query, QUrlPrivate::Scheme, QUrlPrivate::scheme, QUrlPrivate::sectionIsPresent, QUrlPrivate::UserInfo, userInfo(), and QUrlPrivate::validityError().
Referenced by QTest::toString().
QString QUrl::fileName | ( | ComponentFormattingOptions | options = FullyDecoded | ) | const |
Returns the name of the file, excluding the directory path.
Note that, if this QUrl object is given a path ending in a slash, the name of the file is considered empty.
If the path doesn't contain any slash, it is fully returned as the fileName.
Example:
The options argument controls how to format the file name component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Definition at line 2494 of file qurl.cpp.
References QString::lastIndexOf(), and QString::mid().
Referenced by QFileDialogArgs::QFileDialogArgs(), QQmlPropertyCacheCreator< ObjectContainer >::buildMetaObjectRecursively(), QV4::ExecutionEngine::compileModule(), QSSGQmlUtilities::copyTextureAsset(), QV4Debugger::currentExecutionState(), QNetworkReplyWasmImplPrivate::doSendRequest(), QQuickFileDialogImpl::fileName(), QSSGShaderUtils::resolveShader(), AndroidContentFileEngine::rmdir(), QQuickFileDialogImpl::setFileName(), QTextBrowserPrivate::setSource(), and QtAndroidFileDialogHelper::QAndroidPlatformFileDialogHelper::show().
QString QUrl::fragment | ( | ComponentFormattingOptions | options = PrettyDecoded | ) | const |
Returns the fragment of the URL.
To determine if the parsed URL contained a fragment, use hasFragment().
The options argument controls how to format the fragment component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Note that QUrl::FullyDecoded may cause data loss if those non-representable sequences are present. It is recommended to use that value when the result will be used in a non-URL context.
Definition at line 2679 of file qurl.cpp.
References QUrlPrivate::appendFragment(), QUrlPrivate::Fragment, and QUrlPrivate::hasFragment().
Referenced by doRegisterInlineComponentType(), setFragment(), QV4::UrlObject::setHash(), QTextBrowserPrivate::setSource(), QV4::UrlObject::setUrl(), and QV4::UrlCtor::virtualCallAsConstructor().
|
static |
Returns the Unicode form of the given domain name domain, which is encoded in the ASCII Compatible Encoding (ACE). The output can be customized by passing flags with options. The result of this function is considered equivalent to domain.
If the value in domain cannot be encoded, it will be converted to QString and returned.
The ASCII-Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491 and RFC 3492 and updated by the Unicode Technical Standard #46. It is part of the Internationalizing Domain Names in Applications (IDNA) specification, which allows for domain names (like "example.com"
) to be written using non-US-ASCII characters.
Definition at line 3038 of file qurl.cpp.
References ForbidLeadingDot, QString::fromLatin1(), NormalizeAce, and qt_ACE_do().
Referenced by QHostInfo::localDomainName(), and QNetworkCookiePrivate::parseSetCookieHeaderLine().
|
static |
Parses input and returns the corresponding QUrl.
input is assumed to be in encoded form, containing only ASCII characters.
Parses the URL using mode. See setUrl() for more information on this parameter. QUrl::DecodedMode is not permitted in this context.
{QByteArray{~~~}} to make the cast explicit. This is backwards-compatible with old Qt versions.Definition at line 2985 of file qurl.cpp.
References QUrl(), and QString::fromUtf8().
Referenced by QFFmpegMetaData::addEntry(), convertExtendedTypeToJson(), QMacMimeUrl::convertToMime(), dataToUrls(), QLibProxyWrapper::getProxies(), parseAttributeValues(), parseHeaderValue(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QNetworkReplyHttpImplPrivate::sendCacheContents(), and QCborValue::toUrl().
Returns a QUrl representation of localFile, interpreted as a local file.
This function accepts paths separated by slashes as well as the native separator for this platform.
This function also accepts paths with a doubled leading slash (or backslash) to indicate a remote file, as in "//servername/path/to/file.txt". Note that only certain platforms can actually open this file using QFile::open().
An empty localFile leads to an empty URL (since Qt 5.4).
In the first line in snippet above, a file URL is constructed from a local, relative path. A file URL with a relative path only makes sense if there is a base URL to resolve it against. For example:
To resolve such a URL, it's necessary to remove the scheme beforehand:
For this reason, it is better to use a relative URL (that is, no scheme) for relative file paths:
Definition at line 3354 of file qurl.cpp.
References QString::at(), Qt::CaseInsensitive, QString::clear(), DecodedMode, detach(), QStringView::endsWith(), QUrlPrivate::error, fileScheme(), fromNativeSeparators(), QString::indexOf(), QUrlPrivate::InvalidRegNameError, QString::isEmpty(), QString::mid(), QString::prepend(), QString::right(), scheme(), QUrlPrivate::setHost(), setPath(), setScheme(), QString::size(), QStringView::size(), QString::startsWith(), StrictMode, QStringView::toString(), QStringView::truncate(), url, webDavScheme(), and webDavSslTag().
Referenced by MyGame::MyGame(), QFileDialogArgs::QFileDialogArgs(), QQmlComponent::QQmlComponent(), QQuickFolderDialog::QQuickFolderDialog(), QQuickPlatformFolderDialog::QQuickPlatformFolderDialog(), QFileDialogPrivate::_q_pathChanged(), _qt_get_directory(), QCoreTextFontDatabase::addApplicationFont(), QUrlModel::addUrls(), QQuick3DLightmapBaker::bake(), QQmlEngine::baseUrl(), QQuickFolderListModel::componentComplete(), QWindowsMimeURI::convertToMime(), QFileDialogPrivate::createWidgets(), QQuickFolderBreadcrumbBarPrivate::crumbClicked(), QQuickFileDialog::currentFolder(), QQuickFolderListModel::data(), QCocoaFileDialogHelper::directory(), QGtk3FileDialogHelper::directory(), QFileDialog::directoryUrl(), QQmlJavaScriptExpression::evalFunction(), QQmlStandardPaths::findExecutable(), QQuickControlsTestUtils::forEachControl(), fromUserInput(), QFileDialog::getExistingDirectory(), QFileDialog::getOpenFileName(), QFileDialog::getOpenFileNames(), QFileDialog::getSaveFileName(), QQuickFolderBreadcrumbBarPrivate::goUp(), QIOSFileDialog::hide(), AssimpImporter::import(), QQmlPluginImporter::importPlugins(), itemToDialogUrl(), loadFileDialog(), QTextDocument::loadResource(), QQmlStandardPaths::locate(), QQmlImportDatabase::locateLocalQmldir(), main(), main(), makeDocTeamHappyByKeepingExampleCompilable(), QQmlPreviewServiceImpl::messageReceived(), QFileSystemModel::mimeData(), QQuickFolderListModel::parentFolder(), QT_BEGIN_NAMESPACE::parsePlaceResult(), QRhiMetal::pipelineCacheData(), QQmlFindUsagesSupport::process(), QmlGoToDefinitionSupport::process(), QmlGoToTypeDefinitionSupport::process(), qsoundeffectsnippet(), quick_test_main_with_setup(), AVFMediaEncoder::record(), QFFmpegMediaRecorder::record(), QGstreamerMediaEncoder::record(), QWindowsMediaEncoder::record(), QQuickImageBase::resolve2xLocalFile(), QTextBrowserPrivate::resolveUrl(), QFileDialog::restoreState(), QQuickCanvasItem::save(), QFileSelector::select(), QGtk3FileDialogHelper::selectedFiles(), QFileDialog::selectedUrls(), QFileDialog::selectFile(), QFileDialog::setDirectory(), QFileDialogComboBox::setHistory(), QQuickFileDialogImpl::setInitialCurrentFolderAndSelectedFile(), QMediaPlayerPrivate::setMedia(), QRhiMetal::setPipelineCacheData(), QQmlImportInstance::setQmldirContent(), QQuick3DAmbientSound::setSource(), QQuick3DSpatialSound::setSource(), QQuickPlatformFileDialog::show(), QFileDialogComboBox::showPopup(), QAndroidCaptureSession::start(), QQmlDataTest::testFileUrl(), QQuickFolderBreadcrumbBarPrivate::textFieldAccepted(), toUrlList(), QPdfLinkModelPrivate::update(), QQuickIconImagePrivate::updateIcon(), QQuickFileDialogImplPrivate::updateSelectedFile(), QQuickFolderDialogImplPrivate::updateSelectedFolder(), QQuickImageSelector::updateSource(), QWindowsShellItem::url(), QV4::Compiler::Codegen::url(), QQuickImagineStyle::url(), urlForFileName(), QQmlImports::urlFromLocalFileOrQrcOrUrl(), QFileDialogPrivate::userSelectedFiles(), withComponent(), and QQmlStandardPaths::writableLocation().
|
static |
Returns a decoded copy of input.
input is first decoded from percent encoding, then converted from UTF-8 to unicode.
Definition at line 2998 of file qurl.cpp.
References ba, QByteArray::fromPercentEncoding(), QString::fromUtf8(), and QByteArray::size().
|
static |
Converts a list of strings representing urls into a list of urls, using QUrl(str, mode). Note that this means all strings must be urls, not for instance local paths.
Definition at line 3646 of file qurl.cpp.
References QList< T >::append(), QList< T >::reserve(), and str.
|
static |
Returns a valid URL from a user supplied userInput string if one can be deduced.
In the case that is not possible, an invalid QUrl() is returned.
This allows the user to input a URL or a local file path in the form of a plain string. This string can be manually typed into a location bar, obtained from the clipboard, or passed in via command line arguments.
When the string is not already a valid URL, a best guess is performed, making various assumptions.
In the case the string corresponds to a valid file path on the system, a file:// URL is constructed, using QUrl::fromLocalFile().
If that is not the case, an attempt is made to turn the string into a http:// or ftp:// URL. The latter in the case the string starts with 'ftp'. The result is then passed through QUrl's tolerant parser, and in the case or success, a valid QUrl is returned, or else a QUrl().
Definition at line 3743 of file qurl.cpp.
References QUrl(), QFileInfo::absoluteFilePath(), adjustFtpPath(), AssumeLocalFile, Qt::CaseInsensitive, QStringView::compare(), QFileInfo::exists(), fromLocalFile(), ftpScheme(), host(), QString::indexOf(), QDir::isAbsolutePath(), QString::isEmpty(), isIp6(), isRelative(), isValid(), QString::left(), path(), port(), QStringLiteral, scheme(), setHost(), setScheme(), TolerantMode, QString::trimmed(), and url.
Referenced by QSSGRuntimeUtils::applyPropertyValue(), QQmlApplicationEngine::load(), QMediaPlayerPrivate::setMedia(), and QPlaceIcon::url().
bool QUrl::hasFragment | ( | ) | const |
Returns true
if this URL contains a fragment (i.e., if # was seen on it).
Definition at line 2697 of file qurl.cpp.
References QUrlPrivate::hasFragment().
Referenced by QDesktopServices::openUrl(), QWindowsServices::openUrl(), QTextBrowserPrivate::resolveUrl(), and shellExecute().
bool QUrl::hasQuery | ( | ) | const |
Returns true
if this URL contains a Query (i.e., if ? was seen on it).
Definition at line 2510 of file qurl.cpp.
References QUrlPrivate::hasQuery().
Referenced by QUrlQuery::QUrlQuery(), QHttpNetworkRequestPrivate::header(), QV4::UrlObject::search(), and shellExecute().
QString QUrl::host | ( | ComponentFormattingOptions | options = FullyDecoded | ) | const |
Returns the host of the URL if it is defined; otherwise an empty string is returned.
The options argument controls how the hostname will be formatted. The QUrl::EncodeUnicode option will cause this function to return the hostname in the ASCII-Compatible Encoding (ACE) form, which is suitable for use in channels that are not 8-bit clean or that require the legacy hostname (such as DNS requests or in HTTP request headers). If that flag is not present, this function returns the International Domain Name (IDN) in Unicode form, according to the list of permissible top-level domains (see idnWhitelist()).
All other flags are ignored. Host names cannot contain control or percent characters, so the returned value can be considered fully decoded.
Definition at line 2337 of file qurl.cpp.
References QUrlPrivate::appendHost().
Referenced by QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QMacMimeFileUri::convertToMime(), QMacMimeUrl::convertToMime(), QNetworkCookieJar::cookiesForUrl(), QHttpNetworkConnectionPrivate::createAuthorization(), QQmlMetaType::equalBaseUrls(), fromUserInput(), QHttpNetworkConnectionPrivate::handleAuthenticateChallenge(), QHstsPolicy::host(), imageProviderId(), QHstsCache::isKnownHost(), QNetworkCookie::normalize(), QNetworkAccessFileBackend::open(), QHstsPolicyPrivate::operator==(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QNetworkProxyQuery::peerHostName(), qDecodeDataUrl(), setHost(), QV4::UrlObject::setHost(), QV4::UrlObject::setHostname(), QV4::UrlObject::setUrl(), QHttpThreadDelegate::startRequest(), QHstsCache::updateFromHeaders(), QHstsCache::updateKnownHost(), and QNetworkCookieJar::validateCookie().
|
static |
Returns the current whitelist of top-level domains that are allowed to have non-ASCII characters in their compositions.
See setIdnWhitelist() for the rationale of this list.
Definition at line 926 of file qurlidna.cpp.
References i, idn_whitelist, list, QList< T >::reserve(), and user_idn_whitelist.
bool QUrl::isDetached | ( | ) | const |
Definition at line 3298 of file qurl.cpp.
References QBasicAtomicInteger< T >::loadRelaxed(), and QUrlPrivate::ref.
bool QUrl::isEmpty | ( | ) | const |
Returns true
if the URL has no data; otherwise returns false
.
Definition at line 1888 of file qurl.cpp.
References QUrlPrivate::isEmpty().
Referenced by QFileDialogArgs::QFileDialogArgs(), QQmlImports::addFileImport(), QTextHtmlParserNode::applyBackgroundImage(), QNetworkAccessManagerPrivate::authenticationRequired(), QtObject::createComponent(), QQuickPropertyChangesPrivate::decodeBinding(), QGtk3FileDialogHelper::directory(), QHttpNetworkConnectionChannel::ensureConnection(), QQuickItemGrabResultPrivate::ensureImageInCache(), QQuickIcon::ensureRelativeSourceResolved(), QAndroidMetaData::extractMetadata(), QFileDialog::getExistingDirectory(), QFileDialog::getOpenFileName(), QFileDialog::getSaveFileName(), QQuickAnimatedImagePrivate::infoForCurrentFrame(), QQuickIcon::isEmpty(), QPlaceSupplierPrivate::isEmpty(), isValid(), MFPlayerSession::load(), QTextDocument::loadResource(), QQmlComponentPrivate::loadUrl(), QQmlPreviewServiceImpl::messageReceived(), operator=(), QGstreamerMediaPlayer::pause(), QAndroidMediaPlayer::play(), QGstreamerMediaPlayer::play(), QGstreamerMediaPlayer::position(), QFFmpegMediaRecorder::record(), QGstreamerMediaEncoder::record(), QQuickIcon::resolvedSource(), QQmlContextData::resolvedUrl(), QQuickPlatformFileDialog::selectedFiles(), QmlLsp::QQmlCodeModel::setBuildPathsForRootUrl(), QQuickFileDialogImpl::setCurrentFolder(), QQuickDragAttached::setImageSource(), QGstreamerMediaPlayer::setMedia(), AVFMediaPlayer::setMedia(), QFFmpegMediaPlayer::setMedia(), QMediaPlayerPrivate::setMedia(), QAndroidMediaPlayer::setMedia(), QWasmMediaPlayer::setMedia(), AVFAudioDecoder::setSource(), MFAudioDecoderControl::setSource(), QSoundEffect::setSource(), QWasmAudioOutput::setSource(), QWasmVideoOutput::setSource(), AVFAudioDecoder::setSourceDevice(), MFAudioDecoderControl::setSourceDevice(), QQuickPlatformFileDialog::show(), QQmlEnginePrivate::singletonInstance(), QGstreamerAudioDecoder::start(), QQmlFile::status(), QQuick3DLoader::status(), QQmlError::toString(), QQuickFileDialogImplPrivate::updateEnabled(), QQuickFolderDialogImplPrivate::updateEnabled(), QQuick3DCustomMaterial::updateSpatialNode(), QQuick3DTexture::updateSpatialNode(), QSSGQmlUtilities::valueToQml(), and QQmlPropertyPrivate::write().
bool QUrl::isLocalFile | ( | ) | const |
true
if this URL is pointing to a local file path. A URL is a local file path if the scheme is "file".Note that this function considers URLs with hostnames to be local file paths, even if the eventual file path cannot be opened with QFile::open().
Definition at line 3431 of file qurl.cpp.
References QUrlPrivate::isLocalFile().
Referenced by QFileDialogArgs::QFileDialogArgs(), _qt_get_directory(), QWindowsMimeURI::canConvertFromMime(), QMacMimeFileUri::convertFromMime(), QNetworkAccessFileBackendFactory::create(), QWindowsFileDialogHelper::createNativeDialog(), QNetworkAccessManager::createRequest(), MyApplication::event(), QFileDialog::getExistingDirectory(), QFileDialog::getOpenFileName(), QFileDialog::getSaveFileName(), importImp(), QPlatformFileDialogHelper::isSupportedUrl(), itemToDialogUrl(), MFPlayerSession::load(), QQmlComponentPrivate::loadUrl(), matches(), QMimeDatabase::mimeTypeForUrl(), QDesktopServices::openUrl(), QWindowsServices::openUrl(), operator==(), QQuickStyledTextPrivate::parseImageAttributes(), QFileSelector::select(), QFileDialog::selectUrl(), AndroidMediaMetadataRetriever::setDataSource(), QWasmAudioOutput::setSource(), QWasmVideoOutput::setSource(), shellExecute(), QWindowsNativeFileDialogBase::shellItem(), toLocalFile(), QQmlError::toString(), toString(), and v4StackTrace().
bool QUrl::isParentOf | ( | const QUrl & | childUrl | ) | const |
Returns true
if this URL is a parent of childUrl.
childUrl is a child of this URL if the two URLs share the same scheme and authority, and this URL's path is a parent of the path of childUrl.
Definition at line 3441 of file qurl.cpp.
References QString::at(), authority(), QString::endsWith(), QString::isEmpty(), path(), QUrlPrivate::scheme, scheme(), QString::size(), and QString::startsWith().
bool QUrl::isRelative | ( | ) | const |
Returns true
if the URL is relative; otherwise returns false
.
A URL is relative reference if its scheme is undefined; this function is therefore equivalent to calling scheme().isEmpty().
Relative references are defined in RFC 3986 section 4.2.
Definition at line 2797 of file qurl.cpp.
References QUrlPrivate::hasScheme().
Referenced by QTextBrowserPrivate::_q_activateAnchor(), QQmlImportDatabase::addImportPath(), QQmlImportDatabase::addPluginPath(), createImageNode(), QtObject::createQmlObject(), QQuickStackElement::fromString(), fromUserInput(), QQmlTypeLoader::getQmldir(), QQmlTypeLoader::getScript(), QQmlTypeLoader::getType(), QQnxAbstractNavigator::invokeUrl(), QTextDocument::loadResource(), QQmlComponentPrivate::loadUrl(), QV4::QQmlXMLHttpRequestCtor::method_open(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), qmlRegisterSingletonType(), qmlRegisterType(), resolvedUrl(), resolvedUrl(), resolveImagePath(), QTextBrowserPrivate::resolveUrl(), QV4::UrlObject::setHref(), and QQmlPropertyPrivate::write().
bool QUrl::isValid | ( | ) | const |
Returns true
if the URL is non-empty and valid; otherwise returns false
.
The URL is run through a conformance test. Every part of the URL must conform to the standard encoding rules of the URI standard for the URL to be reported as valid.
Definition at line 1874 of file qurl.cpp.
References isEmpty(), QUrlPrivate::NoError, and QUrlPrivate::validityError().
Referenced by TileProvider::TileProvider(), QUrlModel::addUrls(), adjusted(), QSSGRuntimeUtils::applyPropertyValue(), QNetworkDiskCachePrivate::cacheFileName(), QNetworkReplyHttpImplPrivate::checkForRedirect(), checkUrl(), convertToExtendedType(), QQuickDragAttachedPrivate::createMimeData(), QtObject::createQmlObject(), QQuickFileDialog::currentFolder(), QNetworkDiskCache::data(), QWindowsNativeOpenFileDialog::dialogResult(), QTextBrowser::doSetSource(), QQmlCustomParser::evaluateEnum(), MyApplication::event(), QWindowsShellItem::format(), QQuickStackElement::fromString(), fromUserInput(), QQuickFileDialogImplPrivate::handleClick(), QQuickFolderDialogImplPrivate::handleClick(), QHttpNetworkConnectionChannel::handleStatus(), QQnxAbstractNavigator::invokeUrl(), QHstsCache::isKnownHost(), itemToDialogUrl(), QQuickJSContext2DPrototype::method_drawImage(), QXcbMime::mimeConvertToFormat(), QQuickLabsPlatformFileDialog::onShow(), QQuickFileDialog::onShow(), QQuickFolderDialog::onShow(), QDesktopServices::openUrl(), operator<<(), QQuickStackViewPrivate::parseElements(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QQnxMediaPlayer::play(), QNetworkDiskCache::prepare(), QQmlContextData::resolvedUrl(), QWindowsNativeOpenFileDialog::selectedFiles(), QFileDialog::selectUrl(), QV4::UrlObject::setHash(), QFileDialogComboBox::setHistory(), QV4::UrlObject::setHost(), QV4::UrlObject::setHostname(), QV4::UrlObject::setHref(), QV4::UrlObject::setPassword(), QV4::UrlObject::setPathname(), QV4::UrlObject::setPort(), QV4::UrlObject::setProtocol(), QV4::UrlObject::setSearch(), QSoundEffect::setSource(), QTextBrowserPrivate::setSource(), QQuickPdfDocument::setSource(), QV4::UrlObject::setUsername(), QFileDialogComboBox::showPopup(), MFAudioDecoderControl::start(), QQuickFolderBreadcrumbBarPrivate::textFieldAccepted(), QTest::toString(), toString(), QHstsCache::updateFromHeaders(), QHstsCache::updateKnownHost(), QWindowsShellItem::url(), and TestHTTPServer::wait().
bool QUrl::matches | ( | const QUrl & | url, |
FormattingOptions | options | ||
) | const |
Returns true
if this URL and the given url are equal after applying options to both; otherwise returns false
.
This is equivalent to calling adjusted(options) on both URLs and comparing the resulting urls, but faster.
Definition at line 3164 of file qurl.cpp.
References QUrlPrivate::appendPath(), QUrlPrivate::fragment, QUrlPrivate::FullUrl, QUrlPrivate::host, QUrlPrivate::isEmpty(), isLocalFile(), QUrlPrivate::password, QUrlPrivate::Path, QUrlPrivate::port, QUrlPrivate::query, RemoveAuthority, RemoveFragment, RemovePassword, RemovePath, RemovePort, RemoveQuery, RemoveScheme, RemoveUserInfo, QUrlPrivate::scheme, QUrlPrivate::sectionIsPresent, QUrlTwoFlags< E1, E2 >::testFlag(), url, and QUrlPrivate::userName.
Referenced by QNetworkProxyFactory::systemProxyForQuery().
bool QUrl::operator!= | ( | const QUrl & | url | ) | const |
bool QUrl::operator< | ( | const QUrl & | url | ) | const |
Returns true
if this URL is "less than" the given url. This provides a means of ordering URLs.
Definition at line 3073 of file qurl.cpp.
References QString::compare(), QUrlPrivate::fragment, QUrlPrivate::hasFragment(), QUrlPrivate::hasQuery(), QUrlPrivate::host, QUrlPrivate::isEmpty(), QUrlPrivate::password, QUrlPrivate::path, QUrlPrivate::port, QUrlPrivate::query, QUrlPrivate::scheme, url, and QUrlPrivate::userName.
Assigns the specified url to this object.
Definition at line 3263 of file qurl.cpp.
References clear(), detach(), isEmpty(), QUrlPrivate::parse(), TolerantMode, and url.
Assigns the specified url to this object.
Definition at line 3244 of file qurl.cpp.
References clear(), d, qAtomicAssign(), QUrlPrivate::ref, QBasicAtomicInteger< T >::ref(), and url.
bool QUrl::operator== | ( | const QUrl & | url | ) | const |
Returns true
if this URL and the given url are equal; otherwise returns false
.
Definition at line 3127 of file qurl.cpp.
References QUrlPrivate::fragment, QUrlPrivate::FullUrl, QUrlPrivate::host, QUrlPrivate::isEmpty(), isLocalFile(), QUrlPrivate::password, QUrlPrivate::path, QUrlPrivate::port, QUrlPrivate::query, QUrlPrivate::scheme, QUrlPrivate::sectionIsPresent, url, and QUrlPrivate::userName.
QString QUrl::password | ( | ComponentFormattingOptions | options = FullyDecoded | ) | const |
Returns the password of the URL if it is defined; otherwise an empty string is returned.
The options argument controls how to format the user name component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Note that QUrl::FullyDecoded may cause data loss if those non-representable sequences are present. It is recommended to use that value when the result will be used in a non-URL context, such as setting in QAuthenticator or negotiating a login.
Definition at line 2259 of file qurl.cpp.
References QUrlPrivate::appendPassword().
Referenced by QNetworkAccessManagerPrivate::authenticationRequired(), QNetworkReplyWasmImplPrivate::doSendRequest(), QQmlMetaType::equalBaseUrls(), QNetworkAccessAuthenticationManager::fetchCachedCredentials(), QHttpProtocolHandler::sendRequest(), setPassword(), QV4::UrlObject::setPassword(), and QV4::UrlObject::setUrl().
QString QUrl::path | ( | ComponentFormattingOptions | options = FullyDecoded | ) | const |
Returns the path of the URL.
The options argument controls how to format the path component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Note that QUrl::FullyDecoded may cause data loss if those non-representable sequences are present. It is recommended to use that value when the result will be used in a non-URL context, such as sending to an FTP server.
An example of data loss is when you have non-Unicode percent-encoded sequences and use FullyDecoded (the default):
In this example, there will be some level of data loss because the FF
cannot be converted.
Data loss can also occur when the path contains sub-delimiters (such as +
):
Other decoding examples:
Definition at line 2465 of file qurl.cpp.
References QUrlPrivate::appendPath(), and QUrlPrivate::Path.
Referenced by QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QTextBrowserPrivate::_q_documentModified(), QFileDialogPrivate::addDefaultSuffixToUrls(), adjustFtpPath(), QSSGRuntimeUtils::applyPropertyValue(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QMacMimeFileUri::convertToMime(), QMacMimeUrl::convertToMime(), QNetworkCookieJar::cookiesForUrl(), QSSGQmlUtilities::copyTextureAsset(), QWindowsFileDialogHelper::createNativeDialog(), QQmlMetaType::equalBaseUrls(), QNetworkAccessAuthenticationManager::fetchCachedCredentials(), QCoreTextFontDatabaseEngineFactory< T >::fontEngine(), fromUserInput(), QPlaceManagerEngineNokiaV2::getPlaceContent(), importImp(), isParentOf(), isScalableImageFormat(), QAmbientSoundPrivate::load(), SourceResolver::load(), QMimeDatabase::mimeTypeForUrl(), QNetworkCookie::normalize(), QNetworkAccessFileBackend::open(), QAndroidPlatformServices::openUrl(), parseCategory(), processUrlForClassName(), resolveImagePath(), QQuickFolderListModelPrivate::resolvePath(), QTextBrowserPrivate::resolveUrl(), QFileSelector::select(), QFileDialog::selectFile(), QXdgDesktopPortalFileDialog::selectFile(), AndroidMediaMetadataRetriever::setDataSource(), QXdgDesktopPortalFileDialog::setDirectory(), QQuickFileDialogDelegate::setFile(), QMediaPlayerPrivate::setMedia(), QV4::UrlObject::setPathname(), QTextBrowserPrivate::setSource(), QV4::UrlObject::setUrl(), QWindowsNativeFileDialogBase::shellItem(), QQmlError::toString(), QQmlFile::urlToLocalFileOrQrc(), QSSGQmlUtilities::valueToQml(), QV4::UrlCtor::virtualCallAsConstructor(), and QQmlJSImportVisitor::visit().
int QUrl::port | ( | int | defaultPort = -1 | ) | const |
Returns the port of the URL, or defaultPort if the port is unspecified.
Example:
Definition at line 2380 of file qurl.cpp.
References QUrlPrivate::port.
Referenced by QNetworkAccessManager::createRequest(), QQmlMetaType::equalBaseUrls(), fromUserInput(), QNetworkReplyHttpImplPrivate::onRedirected(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QNetworkProxyQuery::peerPort(), QHttpNetworkConnectionPrivate::prepareRequest(), QV4::UrlObject::setHost(), QV4::UrlObject::setPort(), QV4::UrlObject::setUrl(), and QHttpThreadDelegate::startRequest().
QString QUrl::query | ( | ComponentFormattingOptions | options = PrettyDecoded | ) | const |
Returns the query string of the URL if there's a query string, or an empty result if not.
To determine if the parsed URL contained a query string, use hasQuery().
The options argument controls how to format the query component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Note that use of QUrl::FullyDecoded in queries is discouraged, as queries often contain data that is supposed to remain percent-encoded, including the use of the "%2B" sequence to represent a plus character ('+').
Definition at line 2606 of file qurl.cpp.
References QUrlPrivate::appendQuery(), QUrlPrivate::hasQuery(), and QUrlPrivate::Query.
Referenced by QUrlQuery::QUrlQuery(), QQmlMetaType::equalBaseUrls(), QHttpNetworkRequestPrivate::header(), QV4::UrlObject::search(), QV4::UrlObject::setSearch(), QV4::UrlObject::setUrl(), and QV4::UrlCtor::virtualCallAsConstructor().
Returns the result of the merge of this URL with relative.
This URL is used as a base to convert relative to an absolute URL.
If relative is not a relative URL, this function will return relative directly. Otherwise, the paths of the two URLs are merged, and the new URL returned has the scheme and authority of the base URL, but with the merged path, as in the following example:
Calling resolved() with ".." returns a QUrl whose directory is one level higher than the original. Similarly, calling resolved() with "../.." removes two levels from the path. If relative is "/", the path becomes "/".
Definition at line 2722 of file qurl.cpp.
References QUrlPrivate::Authority, detach(), QUrlPrivate::flags, QUrlPrivate::Fragment, QUrlPrivate::fragment, QUrlPrivate::hasAuthority(), QUrlPrivate::hasFragment(), QUrlPrivate::hasQuery(), QUrlPrivate::hasScheme(), QUrlPrivate::host, QString::isEmpty(), QUrlPrivate::IsLocalFile, QUrlPrivate::mergePaths(), QUrlPrivate::password, QUrlPrivate::path, QUrlPrivate::port, qDebug, QUrlPrivate::Query, QUrlPrivate::query, qUtf16Printable, removeDotsFromPath(), QUrlPrivate::Scheme, QUrlPrivate::scheme, QUrlPrivate::sectionIsPresent, QString::startsWith(), url, url(), and QUrlPrivate::userName.
Referenced by QQmlTypeLoader::Blob::importQmldirScripts(), QV4::ExecutionEngine::loadModule(), QTextDocument::loadResource(), QQuickTextDocumentWithImageResources::loadResource(), QQmlComponentPrivate::loadUrl(), QV4::ExecutionEngine::moduleForUrl(), QQuickStyledTextPrivate::parseImageAttributes(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QFFmpegMediaRecorder::record(), QGstreamerMediaEncoder::record(), QQmlImports::resolvedScripts(), QQmlContextData::resolvedUrl(), QTextBrowserPrivate::resolveUrl(), QTextBrowserPrivate::setSource(), QQuick3DAmbientSound::setSource(), QQuick3DSpatialSound::setSource(), TestHTTPServer::url(), and ThreadedTestHTTPServer::url().
QString QUrl::scheme | ( | ) | const |
Returns the scheme of the URL.
If an empty string is returned, this means the scheme is undefined and the URL is then relative.
The scheme can only contain US-ASCII letters or digits, which means it cannot contain any character that would otherwise require encoding. Additionally, schemes are always returned in lowercase form.
Definition at line 1983 of file qurl.cpp.
References QUrlPrivate::scheme.
Referenced by QHttpNetworkReplyPrivate::QHttpNetworkReplyPrivate(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QNetworkReplyHttpImpl::QNetworkReplyHttpImpl(), QTextBrowserPrivate::_q_activateAnchor(), QNetworkReplyImplPrivate::_q_startOperation(), QQmlImportDatabase::addImportPath(), QQmlImportDatabase::addPluginPath(), QUrlModel::addUrls(), adjustFtpPath(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QNetworkCookieJar::cookiesForUrl(), QNetworkAccessFileBackendFactory::create(), createPixmapDataSync(), QNetworkAccessManager::createRequest(), QQmlMetaType::equalBaseUrls(), fromLocalFile(), fromUserInput(), importImp(), QQmlDataTest::initTestCase(), QQmlFile::isLocalFile(), isParentOf(), isScalableImageFormat(), QQmlFile::isSynchronous(), itemToDialogUrl(), QAmbientSoundPrivate::load(), SourceResolver::load(), QQuickPixmap::load(), QTextDocument::loadResource(), QMimeDatabase::mimeTypeForUrl(), QNetworkReplyHttpImplPrivate::onRedirected(), QNetworkAccessFileBackend::open(), QDesktopServices::openUrl(), QIOSServices::openUrl(), QAndroidPlatformServices::openUrl(), QWindowsServices::openUrl(), QQmlError::operator<<(), QHttpNetworkConnectionPrivate::parseRedirectResponse(), QNetworkReplyHttpImplPrivate::postRequest(), QNetworkProxyQuery::protocolTag(), QNetworkAccessManagerPrivate::proxyAuthenticationRequired(), qDecodeDataUrl(), QQmlTypeLoader::qmldirContent(), QNetworkReplyHttpImplPrivate::replyDownloadMetaData(), QQuickFolderListModelPrivate::resolvePath(), QTextBrowserPrivate::resolveUrl(), QFileSelector::select(), QHttpProtocolHandler::sendRequest(), AndroidMediaMetadataRetriever::setDataSource(), QMediaPlayerPrivate::setMedia(), QV4::UrlObject::setProtocol(), setScheme(), QV4::UrlObject::setUrl(), QWindowsNativeFileDialogBase::shellItem(), QAndroidCaptureSession::start(), QQmlApplicationEnginePrivate::startLoad(), QQmlImports::urlFromLocalFileOrQrcOrUrl(), QQmlFile::urlToLocalFileOrQrc(), and QQmlJSImportVisitor::visit().
void QUrl::setAuthority | ( | const QString & | authority, |
ParsingMode | mode = TolerantMode |
||
) |
Sets the authority of the URL to authority.
The authority of a URL is the combination of user info, a host name and a port. All of these elements are optional; an empty authority is therefore valid.
The user info and host are separated by a '@', and the host and port are separated by a ':'. If the user info is empty, the '@' must be omitted; although a stray ':' is permitted if the port is empty.
The following example shows a valid authority string:
The authority data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode (the default), all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters.
This function does not allow mode to be QUrl::DecodedMode. To set fully decoded data, call setUserName(), setPassword(), setHost() and setPort() individually.
Definition at line 2019 of file qurl.cpp.
References authority(), QUrlPrivate::clearError(), DecodedMode, detach(), QString::isNull(), qWarning, QUrlPrivate::sectionIsPresent, QUrlPrivate::setAuthority(), and QString::size().
Referenced by adjusted().
void QUrl::setFragment | ( | const QString & | fragment, |
ParsingMode | mode = TolerantMode |
||
) |
Sets the fragment of the URL to fragment.
The fragment is the last part of the URL, represented by a '#' followed by a string of characters. It is typically used in HTTP for referring to a certain link or point on a page:
The fragment is sometimes also referred to as the URL "reference".
Passing an argument of QString() (a null QString) will unset the fragment. Passing an argument of QString("") (an empty but not null QString) will set the fragment to an empty string (as if the original URL had a lone "#").
The fragment data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode, all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
QUrl::DecodedMode should be used when setting the fragment from a data source which is not a URL or with a fragment obtained by calling fragment() with the QUrl::FullyDecoded formatting option.
Definition at line 2645 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), QUrlPrivate::Fragment, QUrlPrivate::fragment, fragment(), QString::isNull(), parseDecodedComponent(), QUrlPrivate::sectionIsPresent, QUrlPrivate::setFragment(), StrictMode, TolerantMode, and QUrlPrivate::validateComponent().
Referenced by adjusted(), QQuickItemGrabResultPrivate::ensureImageInCache(), QQmlMetaType::inlineComponentUrl(), QV4::ExecutableCompilationUnit::instantiate(), QQmlComponent::loadFromModule(), QV4::QQmlXMLHttpRequestCtor::method_get_responseURL(), QV4::QQmlXMLHttpRequestCtor::method_open(), QV4::UrlObject::setHash(), QTextBrowserPrivate::setSource(), QNetworkDiskCachePrivate::uniqueFileName(), and QV4::UrlCtor::virtualCallAsConstructor().
void QUrl::setHost | ( | const QString & | host, |
ParsingMode | mode = DecodedMode |
||
) |
Sets the host of the URL to host.
The host is part of the authority.
The host data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode, all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
Note that, in all cases, the result of the parsing must be a valid hostname according to STD 3 rules, as modified by the Internationalized Resource Identifiers specification (RFC 3987). Invalid hostnames are not permitted and will cause isValid() to become false.
Definition at line 2286 of file qurl.cpp.
References QUrlPrivate::clearError(), DecodedMode, detach(), QUrlPrivate::error, host(), QUrlPrivate::InvalidIPv6AddressError, QString::isNull(), parseDecodedComponent(), Q_ASSERT, QUrlPrivate::sectionIsPresent, QUrlPrivate::setHost(), and TolerantMode.
Referenced by QHstsPolicy::QHstsPolicy(), QNetworkProxyQuery::QNetworkProxyQuery(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QNetworkAccessManager::connectToHost(), QNetworkAccessManager::connectToHostEncrypted(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QMacMimeFileUri::convertToMime(), QMacMimeUrl::convertToMime(), fromUserInput(), localHostUrl(), QNetworkAccessFileBackend::open(), QHstsPolicy::setHost(), QV4::UrlObject::setHost(), QV4::UrlObject::setHostname(), and QNetworkProxyQuery::setPeerHostName().
|
static |
Sets the whitelist of Top-Level Domains (TLDs) that are allowed to have non-ASCII characters in domains to the value of list.
Note that if you call this function, you need to do so before you start any threads that might access idnWhitelist().
Qt comes with a default list that contains the Internet top-level domains that have published support for Internationalized Domain Names (IDNs) and rules to guarantee that no deception can happen between similarly-looking characters (such as the Latin lowercase letter 'a'
and the Cyrillic equivalent, which in most fonts are visually identical).
This list is periodically maintained, as registrars publish new rules.
This function is provided for those who need to manipulate the list, in order to add or remove a TLD. It is not recommended to change its value for purposes other than testing, as it may expose users to security risks.
Definition at line 964 of file qurlidna.cpp.
References list, and user_idn_whitelist.
void QUrl::setPassword | ( | const QString & | password, |
ParsingMode | mode = DecodedMode |
||
) |
Sets the URL's password to password.
The password is part of the user info element in the authority of the URL, as described in setUserInfo().
The password data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode, all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
QUrl::DecodedMode should be used when setting the password from a data source which is not a URL, such as a password dialog shown to the user or with a password obtained by calling password() with the QUrl::FullyDecoded formatting option.
Definition at line 2224 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), QString::isNull(), parseDecodedComponent(), QUrlPrivate::Password, QUrlPrivate::password, password(), QUrlPrivate::sectionIsPresent, QUrlPrivate::setPassword(), StrictMode, TolerantMode, and QUrlPrivate::validateComponent().
Referenced by adjusted(), QV4::QQmlXMLHttpRequestCtor::method_open(), QV4::UrlObject::setPassword(), and QNetworkDiskCachePrivate::uniqueFileName().
void QUrl::setPath | ( | const QString & | path, |
ParsingMode | mode = DecodedMode |
||
) |
Sets the path of the URL to path.
The path is the part of the URL that comes after the authority but before the query string.
For non-hierarchical schemes, the path will be everything following the scheme declaration, as in the following example:
The path data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode, all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
QUrl::DecodedMode should be used when setting the path from a data source which is not a URL, such as a dialog shown to the user or with a path obtained by calling path() with the QUrl::FullyDecoded formatting option.
Definition at line 2411 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), parseDecodedComponent(), QUrlPrivate::Path, QUrlPrivate::path, QUrlPrivate::setPath(), StrictMode, TolerantMode, and QUrlPrivate::validateComponent().
Referenced by QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QFileDialogPrivate::addDefaultSuffixToUrls(), adjusted(), adjustFtpPath(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QMacMimeFileUri::convertToMime(), QMacMimeUrl::convertToMime(), QQuickItemGrabResultPrivate::ensureImageInCache(), fromLocalFile(), QPlaceManagerEngineNokiaV2::getPlaceContent(), QNetworkAccessFileBackend::open(), QFileDialog::selectFile(), QQuickFileDialogDelegate::setFile(), QV4::UrlObject::setPathname(), urlForFileName(), and QV4::UrlCtor::virtualCallAsConstructor().
void QUrl::setPort | ( | int | port | ) |
Sets the port of the URL to port.
The port is part of the authority of the URL, as described in setAuthority().
port must be between 0 and 65535 inclusive. Setting the port to -1 indicates that the port is unspecified.
Definition at line 2355 of file qurl.cpp.
References QUrlPrivate::clearError(), detach(), QUrlPrivate::Host, QUrlPrivate::InvalidPortError, QString::number(), QUrlPrivate::port, QUrlPrivate::sectionIsPresent, and QUrlPrivate::setError().
Referenced by QNetworkProxyQuery::QNetworkProxyQuery(), adjusted(), QNetworkAccessManager::connectToHost(), QNetworkAccessManager::connectToHostEncrypted(), QNetworkAccessManager::createRequest(), localHostUrl(), QNetworkReplyHttpImplPrivate::onRedirected(), QV4::UrlObject::setHost(), QNetworkProxyQuery::setPeerPort(), QV4::UrlObject::setPort(), and QHttpThreadDelegate::startRequest().
void QUrl::setQuery | ( | const QString & | query, |
ParsingMode | mode = TolerantMode |
||
) |
Sets the query string of the URL to query.
This function is useful if you need to pass a query string that does not fit into the key-value pattern, or that uses a different scheme for encoding special characters than what is suggested by QUrl.
Passing a value of QString() to query (a null QString) unsets the query completely. However, passing a value of QString("") will set the query to an empty value, as if the original URL had a lone "?".
The query data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode, all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
Query strings often contain percent-encoded sequences, so use of DecodedMode is discouraged. One special sequence to be aware of is that of the plus character ('+'). QUrl does not convert spaces to plus characters, even though HTML forms posted by web browsers do. In order to represent an actual plus character in a query, the sequence "%2B" is usually used. This function will leave "%2B" sequences untouched in TolerantMode or StrictMode.
Definition at line 2547 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), parseDecodedComponent(), QUrlPrivate::Query, QUrlPrivate::query, QUrlPrivate::sectionIsPresent, QUrlPrivate::setQuery(), StrictMode, TolerantMode, and QUrlPrivate::validateComponent().
Referenced by adjusted(), GeoRoutingManagerEngineEsri::calculateRoute(), GeoCodingManagerEngineEsri::geocode(), QGeoCodingManagerEngineOsm::geocode(), QPlaceManagerEngineNokiaV2::getPlaceContent(), QPlaceManagerEngineNokiaV2::getPlaceDetails(), QGeoRouteParserOsrmV5Private::requestUrl(), QGeoRouteParserOsrmV4Private::requestUrl(), GeoCodingManagerEngineEsri::reverseGeocode(), QGeoCodingManagerEngineOsm::reverseGeocode(), QPlaceManagerEngineNokiaV2::search(), PlaceManagerEngineEsri::search(), QPlaceManagerEngineOsm::search(), QPlaceManagerEngineNokiaV2::searchSuggestions(), QV4::UrlObject::setSearch(), and QV4::UrlCtor::virtualCallAsConstructor().
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
This function reconstructs the query string from the QUrlQuery object and sets on this QUrl object. This function does not have parsing parameters because the QUrlQuery contains data that is already parsed.
Definition at line 2576 of file qurl.cpp.
References QUrlPrivate::clearError(), detach(), QUrlPrivate::Query, QUrlPrivate::query, and QUrlPrivate::sectionIsPresent.
Sets the scheme of the URL to scheme.
As a scheme can only contain ASCII characters, no conversion or decoding is done on the input. It must also start with an ASCII letter.
The scheme describes the type (or protocol) of the URL. It's represented by one or more ASCII characters at the start the URL.
A scheme is strictly \l {RFC 3986}-compliant: \tt {scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )}
The following example shows a URL where the scheme is "ftp":
To set the scheme, the following call is used:
The scheme can also be empty, in which case the URL is interpreted as relative.
Definition at line 1959 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), detach(), QUrlPrivate::flags, QString::isEmpty(), QUrlPrivate::scheme, scheme(), QUrlPrivate::sectionIsPresent, QUrlPrivate::setScheme(), and QString::size().
Referenced by QNetworkProxyQuery::QNetworkProxyQuery(), QNetworkProxyQuery::QNetworkProxyQuery(), adjusted(), QNetworkAccessManager::connectToHost(), QNetworkAccessManager::connectToHostEncrypted(), QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QNetworkAccessManager::createRequest(), QQuickItemGrabResultPrivate::ensureImageInCache(), fromLocalFile(), fromUserInput(), QTextDocument::loadResource(), QQmlComponentPrivate::loadUrl(), localHostUrl(), QNetworkReplyHttpImplPrivate::onRedirected(), QAndroidPlatformServices::openUrl(), QV4::UrlObject::setProtocol(), QNetworkProxyQuery::setProtocolTag(), QHttpThreadDelegate::startRequest(), and urlForFileName().
void QUrl::setUrl | ( | const QString & | url, |
ParsingMode | parsingMode = TolerantMode |
||
) |
Parses url and sets this object to that value.
QUrl will automatically percent encode all characters that are not allowed in a URL and decode the percent-encoded sequences that represent an unreserved character (letters, digits, hyphens, underscores, dots and tildes). All other characters are left in their original forms.
Parses the url using the parser mode parsingMode. In TolerantMode (the default), QUrl will correct certain mistakes, notably the presence of a percent character ('') not followed by two hexadecimal digits, and it will accept any character in any position. In StrictMode, encoding mistakes will not be tolerated and QUrl will also check that certain forbidden characters are not present in unencoded form. If an error is detected in StrictMode, isValid() will return false. The parsing mode DecodedMode is not permitted in this context and will produce a run-time warning.
Definition at line 1926 of file qurl.cpp.
References DecodedMode, detach(), QUrlPrivate::parse(), qWarning, and url.
Referenced by QUrl(), QQuickAnimatedImagePrivate::infoForCurrentFrame(), and operator>>().
void QUrl::setUserInfo | ( | const QString & | userInfo, |
ParsingMode | mode = TolerantMode |
||
) |
Sets the user info of the URL to userInfo.
The user info is an optional part of the authority of the URL, as described in setAuthority().
The user info consists of a user name and optionally a password, separated by a ':'. If the password is empty, the colon must be omitted. The following example shows a valid user info string:
The userInfo data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode (the default), all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters.
This function does not allow mode to be QUrl::DecodedMode. To set fully decoded data, call setUserName() and setPassword() individually.
Definition at line 2090 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), QString::isNull(), QUrlPrivate::password, qWarning, QUrlPrivate::sectionIsPresent, QUrlPrivate::setUserInfo(), QByteArrayView::size(), StrictMode, QString::trimmed(), QUrlPrivate::UserInfo, userInfo(), QUrlPrivate::userName, and QUrlPrivate::validateComponent().
Referenced by adjusted(), and QHttpProtocolHandler::sendRequest().
void QUrl::setUserName | ( | const QString & | userName, |
ParsingMode | mode = DecodedMode |
||
) |
Sets the URL's user name to userName.
The userName is part of the user info element in the authority of the URL, as described in setUserInfo().
The userName data is interpreted according to mode: in StrictMode, any '' characters must be followed by exactly two hexadecimal characters and some characters (including space) are not allowed in undecoded form. In TolerantMode (the default), all characters are accepted in undecoded form and the tolerant parser will correct stray '' not followed by two hex characters. In DecodedMode, '' stand for themselves and encoded characters are not possible.
QUrl::DecodedMode should be used when setting the user name from a data source which is not a URL, such as a password dialog shown to the user or with a user name obtained by calling userName() with the QUrl::FullyDecoded formatting option.
Definition at line 2161 of file qurl.cpp.
References QString::clear(), QUrlPrivate::clearError(), DecodedMode, detach(), QString::isNull(), parseDecodedComponent(), QUrlPrivate::sectionIsPresent, QUrlPrivate::setUserName(), StrictMode, TolerantMode, QUrlPrivate::UserName, QUrlPrivate::userName, userName(), and QUrlPrivate::validateComponent().
Referenced by QV4::QQmlXMLHttpRequestCtor::method_open(), and QV4::UrlObject::setUsername().
Swaps URL other with this URL. This operation is very fast and never fails.
Definition at line 159 of file qurl.h.
References d, other(), and qt_ptr_swap().
|
static |
Returns the ASCII Compatible Encoding of the given domain name domain. The output can be customized by passing flags with options. The result of this function is considered equivalent to domain.
The ASCII-Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491 and RFC 3492 and updated by the Unicode Technical Standard #46. It is part of the Internationalizing Domain Names in Applications (IDNA) specification, which allows for domain names (like "example.com"
) to be written using non-US-ASCII characters.
This function returns an empty QByteArray if domain is not a valid hostname. Note, in particular, that IPv6 literals are not valid domain names.
Definition at line 3061 of file qurl.cpp.
References ForbidLeadingDot, qt_ACE_do(), ToAceOnly, and QString::toLatin1().
Referenced by QSslSocketPrivate::isMatchingHostname(), QSslSocketPrivate::isMatchingHostname(), QHostInfoAgent::lookup(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QHttpNetworkConnectionPrivate::prepareRequest(), qt_socks5_set_host_name_and_port(), QHttpSocketEngine::slotSocketConnected(), and QNetworkCookie::toRawForm().
QString QUrl::toDisplayString | ( | FormattingOptions | options = FormattingOptions(PrettyDecoded) | ) | const |
Returns a human-displayable string representation of the URL. The output can be customized by passing flags with options. The option RemovePassword is always enabled, since passwords should never be shown back to users.
With the default options, the resulting QString can be passed back to a QUrl later on, but any password that was present initially will be lost.
Definition at line 2903 of file qurl.cpp.
References RemovePassword, and toString().
Referenced by operator<<().
QByteArray QUrl::toEncoded | ( | FormattingOptions | options = FullyEncoded | ) | const |
Returns the encoded representation of the URL if it's valid; otherwise an empty QByteArray is returned.
The output can be customized by passing flags with options.
The user info, path and fragment are all converted to UTF-8, and all non-ASCII characters are then percent encoded. The host name is encoded using Punycode.
Definition at line 2964 of file qurl.cpp.
References FullyDecoded, FullyEncoded, QString::toLatin1(), and toString().
Referenced by QMacMimeFileUri::convertFromMime(), QMacMimeUrl::convertFromMime(), QPdfEngine::drawHyperlink(), QLibProxyWrapper::getProxies(), operator<<(), parseAttributeValues(), QQmlFindUsagesSupport::process(), QmlGoToDefinitionSupport::process(), QmlGoToTypeDefinitionSupport::process(), Q_LOGGING_CATEGORY(), QGstreamerMediaPlayer::setMedia(), AVFMediaPlayer::setMedia(), QGstreamerAudioDecoder::start(), AVFMediaPlayer::streamReady(), QTest::toString(), and QNetworkDiskCachePrivate::uniqueFileName().
QString QUrl::toLocalFile | ( | ) | const |
Returns the path of this URL formatted as a local file path.
The path returned will use forward slashes, even if it was originally created from one with backslashes.
If this URL contains a non-empty hostname, it will be encoded in the returned value in the form found on SMB networks (for example, "//servername/path/to/file.txt").
Note: if the path component of this URL contains a non-UTF-8 binary sequence (such as %80), the behaviour of this function is undefined.
Definition at line 3411 of file qurl.cpp.
References FullyDecoded, isLocalFile(), and QUrlPrivate::toLocalFile().
Referenced by QFileDialogArgs::QFileDialogArgs(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QFileDialogPrivate::_q_goToUrl(), _qt_get_directory(), QUrlModel::addUrls(), WorkspaceHandlers::clientInitialized(), QWindowsMimeURI::convertFromMime(), QWindowsFileDialogHelper::createNativeDialog(), MyApplication::event(), QWindowsXpNativeFileDialog::existingDirCallback(), QFileDialog::getExistingDirectory(), QFileDialog::getOpenFileName(), QFileDialog::getSaveFileName(), QQuickFileDialogImplPrivate::handleClick(), importImp(), QTextDocument::loadResource(), QQmlComponentPrivate::loadUrl(), QMimeDatabase::mimeTypeForUrl(), QNetworkAccessFileBackend::open(), QHaikuServices::openDocument(), QGstreamerMediaEncoder::record(), QTextBrowserPrivate::resolveUrl(), QQuickCanvasItem::save(), QCocoaFileDialogHelper::selectFile(), QFileDialog::selectUrl(), QUrlModel::setData(), QGtk3FileDialogHelper::setDirectory(), QWidgetPlatformFileDialog::setDirectory(), QWasmAudioOutput::setSource(), QWasmVideoOutput::setSource(), shellExecute(), QWindowsNativeFileDialogBase::shellItem(), QIOSFileDialog::show(), QQnxPlatformCamera::startVideoRecording(), QAndroidCaptureSession::stop(), QmlLsp::QQmlCodeModel::url2Path(), QQmlFile::urlToLocalFileOrQrc(), and v4StackTrace().
|
static |
Returns an encoded copy of input.
input is first converted to UTF-8, and all ASCII-characters that are not in the unreserved group are percent encoded. To prevent characters from being percent encoded pass them to exclude. To force characters to be percent encoded pass them to include.
Unreserved is defined as: \tt {ALPHA / DIGIT / "-" / "." / "_" / "~"}
Definition at line 3016 of file qurl.cpp.
References QByteArray::toPercentEncoding().
Referenced by QV4::UrlSearchParamsPrototype::method_toString(), DocumentFile::parseFromAnyUri(), parseUri(), and DocumentFile::rename().
QString QUrl::toString | ( | FormattingOptions | options = FormattingOptions(PrettyDecoded) | ) | const |
Returns a string representation of the URL.
The output can be customized by passing flags with options. The option QUrl::FullyDecoded is not permitted in this function since it would generate ambiguous data.
The default formatting option is \l{QUrl::FormattingOptions}{PrettyDecoded}.
Definition at line 2828 of file qurl.cpp.
References ~QUrl(), QUrlPrivate::appendAuthority(), QUrlPrivate::appendFragment(), QUrlPrivate::appendPath(), QUrlPrivate::appendQuery(), DecodeReserved, EncodeReserved, QUrlPrivate::FullUrl, FullyDecoded, QUrlPrivate::hasAuthority(), QUrlPrivate::hasFragment(), QUrlPrivate::hasQuery(), QUrlPrivate::hasScheme(), isLocalFile(), isValid(), QUrlPrivate::path, PreferLocalFile, qWarning, RemoveAuthority, RemoveFragment, RemovePath, RemoveQuery, RemoveScheme, QUrlPrivate::scheme, QString::startsWith(), QUrlTwoFlags< E1, E2 >::testFlag(), QUrlPrivate::toLocalFile(), and url.
Referenced by QNetworkReplyDataImpl::QNetworkReplyDataImpl(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QQmlDataBlob::addDependency(), QQmlImports::addFileImport(), QQmlImports::addInlineComponentImport(), checkUrl(), QV4::ExecutionEngine::compileModule(), QV4::ExecutionEngine::compileModule(), convertExtendedTypeToJson(), QWindowsMimeURI::convertFromMime(), convertToExtendedType(), QSSGQmlUtilities::copyTextureAsset(), QNetworkAccessFileBackendFactory::create(), QQuickStackViewPrivate::createElement(), QV4::Script::createFromFileOrCache(), createPixmapDataSync(), QNetworkReplyWasmImplPrivate::doSendRequest(), dumpAttributeVariant(), QQmlDataBlob::finalUrlString(), findCompositeSingletons(), QHttpThreadDelegate::finishedSlot(), QJsonValue::fromVariant(), QFileDialog::getExistingDirectory(), QFileDialog::getOpenFileName(), QFileDialog::getOpenFileNames(), QFileDialog::getSaveFileName(), imageId(), QV4::ExecutableCompilationUnit::instantiate(), QQnxAbstractNavigator::invokeUrl(), launchMail(), SourceResolver::load(), QQmlComponentPrivate::loadUrl(), QQmlPreviewPosition::loadWindowPositionSettings(), QQmlImportDatabase::locateLocalQmldir(), QV4::QQmlXMLHttpRequestCtor::method_get_responseURL(), msgShellExecuteFailed(), QNetworkAccessFileBackend::open(), QPlatformServices::openDocument(), QPlatformServices::openUrl(), QAndroidPlatformServices::openUrl(), QHaikuServices::openUrl(), QWasmServices::openUrl(), openWebBrowser(), Q_LOGGING_CATEGORY(), readImage(), AVFMediaEncoder::record(), QV4::Compiler::Codegen::referenceForName(), scanImports(), QQmlContext::setBaseUrl(), QQmlImports::setBaseUrl(), AndroidMediaPlayer::setDataSource(), AndroidMediaMetadataRetriever::setDataSource(), QWindowsFileDialogHelper::setDirectory(), QV4::UrlObject::setHash(), QV4::UrlObject::setHost(), QV4::UrlObject::setHostname(), QV4::UrlObject::setPassword(), QV4::UrlObject::setPathname(), QV4::UrlObject::setPort(), QV4::UrlObject::setProtocol(), QQmlImportInstance::setQmldirContent(), QV4::UrlObject::setSearch(), QWasmAudioOutput::setSource(), QWasmVideoOutput::setSource(), QTextBrowserPrivate::setSource(), QNdefNfcUriRecord::setUri(), QV4::UrlObject::setUrl(), QV4::UrlObject::setUsername(), QQuickShaderEffectPrivate::shaderCodePrepared(), shellExecute(), QWindowsNativeFileDialogBase::shellItem(), QtAndroidFileDialogHelper::QAndroidPlatformFileDialogHelper::show(), QAndroidCaptureSession::start(), statusCodeFromHttp(), QNetworkReplyWasmImplPrivate::statusCodeFromHttp(), QuickTestResult::stringify(), QHttpThreadDelegate::synchronousFinishedSlot(), QQmlDebugTranslation::TranslationIssue::toDebugString(), toDisplayString(), toEncoded(), QQmlError::toString(), QPdfLink::toString(), toStringList(), QPdfLinkModelPrivate::update(), url(), QQmlDataBlob::urlString(), TestHTTPServer::urlString(), ThreadedTestHTTPServer::urlString(), QQmlFile::urlToLocalFileOrQrc(), v4StackTrace(), QV4::UrlCtor::virtualCallAsConstructor(), and writeAttribute().
|
static |
Converts a list of urls into a list of QString objects, using toString(options).
Definition at line 3630 of file qurl.cpp.
References QList< T >::size(), toString(), and url.
QString QUrl::url | ( | FormattingOptions | options = FormattingOptions(PrettyDecoded) | ) | const |
Returns a string representation of the URL.
The output can be customized by passing flags with options. The option QUrl::FullyDecoded is not permitted in this function since it would generate ambiguous data.
The resulting QString can be passed back to a QUrl later on.
Synonym for toString(options).
Definition at line 2814 of file qurl.cpp.
References toString().
Referenced by QV4::QQmlXMLHttpRequestCtor::method_get_responseURL(), QV4::QQmlXMLHttpRequestCtor::method_open(), qDecodeDataUrl(), resolved(), QQmlContextData::resolvedUrl(), QPlaceManagerEngineOsm::search(), AVFMediaPlayer::setMedia(), QMediaPlayerPrivate::setMedia(), QNetworkCacheMetaData::setUrl(), QNetworkAccessBackend::url(), QNetworkReply::url(), QQuickPixmap::url(), and QHttpNetworkReply::url().
QString QUrl::userInfo | ( | ComponentFormattingOptions | options = PrettyDecoded | ) | const |
Returns the user info of the URL, or an empty string if the user info is undefined.
This function returns an unambiguous value, which may contain that characters still percent-encoded, plus some control sequences not representable in decoded form in QString.
The options argument controls how to format the user info component. The value of QUrl::FullyDecoded is not permitted in this function. If you need to obtain fully decoded data, call userName() and password() individually.
Definition at line 2126 of file qurl.cpp.
References QUrlPrivate::appendUserInfo(), FullyDecoded, qWarning, and QUrlPrivate::UserInfo.
Referenced by QNetworkReplyWasmImplPrivate::doSendRequest(), errorString(), QHttpNetworkConnectionPrivate::fillPipeline(), QHttpProtocolHandler::sendRequest(), and setUserInfo().
QString QUrl::userName | ( | ComponentFormattingOptions | options = FullyDecoded | ) | const |
Returns the user name of the URL if it is defined; otherwise an empty string is returned.
The options argument controls how to format the user name component. All values produce an unambiguous result. With QUrl::FullyDecoded, all percent-encoded sequences are decoded; otherwise, the returned value may contain some percent-encoded sequences for some control sequences not representable in decoded form in QString.
Note that QUrl::FullyDecoded may cause data loss if those non-representable sequences are present. It is recommended to use that value when the result will be used in a non-URL context, such as setting in QAuthenticator or negotiating a login.
Definition at line 2196 of file qurl.cpp.
References QUrlPrivate::appendUserName().
Referenced by QNetworkAccessManagerPrivate::authenticationRequired(), QNetworkReplyWasmImplPrivate::doSendRequest(), QQmlMetaType::equalBaseUrls(), QHttpProtocolHandler::sendRequest(), QV4::UrlObject::setUrl(), setUserName(), and QV4::UrlObject::setUsername().
|
related |
\macro QT_NO_URL_CAST_FROM_STRING
Disables automatic conversions from QString (or char *) to QUrl.
Compiling your code with this define is useful when you have a lot of code that uses QString for file names and you wish to convert it to use QUrl for network transparency. In any code that uses QUrl, it can help avoid missing QUrl::resolved() calls, and other misuses of QString to QUrl conversions.
For example, if you have code like
you can rewrite it as
Constructs a URL by parsing url. Note this constructor expects a proper URL or URL-Reference and will not attempt to guess intent. For example, the following declaration:
Will construct a valid URL but it may not be what one expects, as the scheme() part of the input is missing. For a string like the above, applications may want to use fromUserInput(). For this constructor or setUrl(), the following is probably what was intended:
QUrl will automatically percent encode all characters that are not allowed in a URL and decode the percent-encoded sequences that represent an unreserved character (letters, digits, hyphens, underscores, dots and tildes). All other characters are left in their original forms.
Parses the url using the parser mode parsingMode. In TolerantMode (the default), QUrl will correct certain mistakes, notably the presence of a percent character ('') not followed by two hexadecimal digits, and it will accept any character in any position. In StrictMode, encoding mistakes will not be tolerated and QUrl will also check that certain forbidden characters are not present in unencoded form. If an error is detected in StrictMode, isValid() will return false. The parsing mode DecodedMode is not permitted in this context.
Example:
To construct a URL from an encoded string, you can also use fromEncoded():
Both functions are equivalent and, in Qt 5, both functions accept encoded data. Usually, the choice of the QUrl constructor or setUrl() versus fromEncoded() will depend on the source data: the constructor and setUrl() take a QString, whereas fromEncoded takes a QByteArray.
|
related |
|
related |
Reads a url into url from the stream in and returns a reference to the stream.
Definition at line 3485 of file qurl.cpp.
References QString::fromLatin1(), setUrl(), and url.
|
friend |