QUrl 类

QUrl 类提供操控 URL 的方便接口。 更多...

头: #include <QUrl>
qmake: QT += core

注意: 此类的所有函数 可重入 .

公共类型

enum ComponentFormattingOption { PrettyDecoded, EncodeSpaces, EncodeUnicode, EncodeDelimiters, EncodeReserved, …, FullyDecoded }
flags ComponentFormattingOptions
flags FormattingOptions
enum ParsingMode { TolerantMode, StrictMode, DecodedMode }
enum UrlFormattingOption { None, RemoveScheme, RemovePassword, RemoveUserInfo, RemovePort, …, NormalizePathSegments }
enum UserInputResolutionOption { DefaultResolution, AssumeLocalFile }
flags UserInputResolutionOptions

公共函数

QUrl (QUrl && other )
QUrl (const QString & url , QUrl::ParsingMode parsingMode = TolerantMode)
QUrl (const QUrl & other )
QUrl ()
QUrl & operator= (QUrl && other )
QUrl & operator= (const QString & url )
QUrl & operator= (const QUrl & url )
~QUrl ()
QUrl adjusted (QUrl::FormattingOptions options ) const
QString authority (QUrl::ComponentFormattingOptions options = PrettyDecoded) const
void clear ()
QString errorString () const
QString fileName (QUrl::ComponentFormattingOptions options = FullyDecoded) const
QString fragment (QUrl::ComponentFormattingOptions options = PrettyDecoded) const
bool hasFragment () const
bool hasQuery () const
QString host (QUrl::ComponentFormattingOptions options = FullyDecoded) const
bool isEmpty () const
bool isLocalFile () const
bool isParentOf (const QUrl & childUrl ) const
bool isRelative () const
bool isValid () const
bool 匹配 (const QUrl & url , QUrl::FormattingOptions options ) const
QString password (QUrl::ComponentFormattingOptions options = FullyDecoded) const
QString path (QUrl::ComponentFormattingOptions options = FullyDecoded) const
int port (int defaultPort = -1) const
QString query (QUrl::ComponentFormattingOptions options = PrettyDecoded) const
QUrl resolved (const QUrl & relative ) const
QString scheme () const
void setAuthority (const QString & authority , QUrl::ParsingMode mode = TolerantMode)
void setFragment (const QString & fragment , QUrl::ParsingMode mode = TolerantMode)
void setHost (const QString & host , QUrl::ParsingMode mode = DecodedMode)
void setPassword (const QString & password , QUrl::ParsingMode mode = DecodedMode)
void setPath (const QString & path , QUrl::ParsingMode mode = DecodedMode)
void setPort (int port )
void setQuery (const QString & query , QUrl::ParsingMode mode = TolerantMode)
void setQuery (const QUrlQuery & query )
void setScheme (const QString & scheme )
void setUrl (const QString & url , QUrl::ParsingMode parsingMode = TolerantMode)
void setUserInfo (const QString & userInfo , QUrl::ParsingMode mode = TolerantMode)
void setUserName (const QString & userName , QUrl::ParsingMode mode = DecodedMode)
void swap (QUrl & other )
CFURLRef toCFURL () const
QString toDisplayString (QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const
QByteArray toEncoded (QUrl::FormattingOptions options = FullyEncoded) const
QString toLocalFile () const
NSURL * toNSURL () const
QString toString (QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const
QString url (QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const
QString userInfo (QUrl::ComponentFormattingOptions options = PrettyDecoded) const
QString userName (QUrl::ComponentFormattingOptions options = FullyDecoded) const
bool operator!= (const QUrl & url ) const
bool operator== (const QUrl & url ) const

静态公共成员

QString fromAce (const QByteArray & domain )
QUrl fromCFURL (CFURLRef url )
QUrl fromEncoded (const QByteArray & input , QUrl::ParsingMode parsingMode = TolerantMode)
QUrl fromLocalFile (const QString & localFile )
QUrl fromNSURL (const NSURL * url )
QString fromPercentEncoding (const QByteArray & input )
QList<QUrl> fromStringList (const QStringList & urls , QUrl::ParsingMode mode = TolerantMode)
QUrl fromUserInput (const QString & userInput )
QUrl fromUserInput (const QString & userInput , const QString & workingDirectory , QUrl::UserInputResolutionOptions options = DefaultResolution)
QStringList idnWhitelist ()
void setIdnWhitelist (const QStringList & list )
QByteArray toAce (const QString & domain )
QByteArray toPercentEncoding (const QString & input , const QByteArray & exclude = QByteArray(), const QByteArray & 包括 = QByteArray())
QStringList toStringList (const QList<QUrl> & urls , QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded))
QDataStream & operator<< (QDataStream & out , const QUrl & url )
QDataStream & operator>> (QDataStream & in , QUrl & url )

QT_NO_URL_CAST_FROM_STRING

详细描述

它可以剖析和构造编码和未编码形式的 URL。QUrl 还支持 IDN (国际化域名)。

使用 QUrl 的最常见方式是凭借构造函数来初始化通过传递 QString 。否则, setUrl () 也可以使用。

URL 可以按 2 种形式表示:已编码或未编码。未编码表示适合展示给用户,而编码表示通常是发送给 Web 服务器的。例如,未编码 URL http://bühler.example.com/List of applicants.xml 将作为 http://xn--bhler-kva.example.com/List%20of%20applicants.xml 被发送给服务器。

URL 也可以逐段构造通过调用 setScheme (), setUserName (), setPassword (), setHost (), setPort (), setPath (), setQuery () 和 setFragment ()。还有一些方便函数: setAuthority () 设置用户名、口令、主机和端口。 setUserInfo () sets the user name and password at once.

调用 isValid () 以校验 URL 是否有效。可以完成这在构建 URL 期间的任何时候。若 isValid () 返回 false ,应该 clear () URL 在继续进行之前,或开始通过剖析新 URL 采用 setUrl ().

构造查询尤其方便,透过使用 QUrlQuery 类及其方法 QUrlQuery::setQueryItems (), QUrlQuery::addQueryItem () 和 QUrlQuery::removeQueryItem ()。使用 QUrlQuery::setQueryDelimiters () 以定制用于生成查询字符串的定界符。

为方便生成编码 URL 字符串或查询字符串,有 2 个静态函数称为 fromPercentEncoding () 和 toPercentEncoding (),处理百分比编码和解码 QString 对象。

fromLocalFile () 通过剖析本地文件路径构造 QUrl。 toLocalFile () 将 URL 转换为本地文件路径。

人类可读 URL 表示的抓取是采用 toString ()。此表示适合按未编码形式向用户显示 URL。不管怎样,返回编码形式通过 toEncoded (),可供内部使用:传递给 Web 服务器、邮件客户端、等。2 种格式在技术上是正确的,且明确表示相同 URL -- 事实上,传递形式给 QUrl 的构造函数或 setUrl () 将产生相同 QUrl 对象。

QUrl 符合的 URI 规范来自 RFC 3986 (URI 统一资源标识符:通用句法),而包括的方案扩展来自 RFC 1738 (URL 统一资源定位符)。QUrl 中的大小写折叠规则符合 RFC 3491 (Nameprep:用于 IDN (国际化域名) 的 Stringprep Profile)。它还兼容 文件 URI (统一资源标识符) 规范 来自 freedesktop.org,前提是区域设置编码文件名使用 UTF-8 (IDN 要求)。

相对 URL vs 相对路径

调用 isRelative () 将返回 URL 是否是相对的。相对 URL 没有 scheme 。例如:

    qDebug() << QUrl("main.qml").isRelative();          // true: no scheme
    qDebug() << QUrl("qml/main.qml").isRelative();      // true: no scheme
    qDebug() << QUrl("file:main.qml").isRelative();     // false: has "file" scheme
    qDebug() << QUrl("file:qml/main.qml").isRelative(); // false: has "file" scheme
					

预告,URL 可以是绝对的当包含相对路径时,反之亦然:

    // Absolute URL, relative path
    QUrl url("file:file.txt");
    qDebug() << url.isRelative();                 // false: has "file" scheme
    qDebug() << QDir::isAbsolutePath(url.path()); // false: relative path
    // Relative URL, absolute path
    url = QUrl("/home/user/file.txt");
    qDebug() << url.isRelative();                 // true: has no scheme
    qDebug() << QDir::isAbsolutePath(url.path()); // true: absolute path
					

可以解析相对 URL,通过将其作为自变量传递给 resolved (),返回绝对 URL。 isParentOf () 用于确定一个 URL 是否为另一个的父级。

错误检查

QUrl 能检测许多 URL 错误当剖析或设置 URL 组件采用单独 setter 方法 (像 setScheme (), setHost () 或 setPath ())。若剖析或 setter 函数成功,将丢弃任何先前记录的错误条件。

默认情况下,QUrl setter 方法运转于 QUrl::TolerantMode ,这意味着他们接受一些常见差错和数据过失表示。替代剖析方法是 QUrl::StrictMode , 应用进一步校验。见 QUrl::ParsingMode 用于描述剖析模式的差异。

QUrl 仅校验是否与 URL 规范保持一致。它不会试着验证高级协议 URL 的式是否是其它处理程序所期望的。例如,以下 URI 被 QUrl 认为是有效的,即使它们没有意义 (当使用时):

  • "http:/filename.html"
  • "mailto://example.com"

当剖析器遇到错误时,它信号事件通过使 isValid () 返回 false 和 toString () / toEncoded () 返回空字符串。若有必要向用户展示 URL 剖析为什么失败的原因,可以从 QUrl 获得错误条件通过调用 errorString ()。注意:此消息是高度技术性的,且对最终用户可能没有意义。

QUrl 只能记录一种错误条件。若发现多个错误,则不确定要报告哪个错误。

字符转换

遵循这些规则以避免错误字符转换,当处理 URL 和字符串时:

成员类型文档编制

enum QUrl:: ComponentFormattingOption
flags QUrl:: ComponentFormattingOptions

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 当用于 toString () 和 toEncoded ().

常量 描述
QUrl::PrettyDecoded 0x000000 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.
QUrl::EncodeSpaces 0x100000 Leave space characters in their encoded form ("%20").
QUrl::EncodeUnicode 0x200000 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).
QUrl::EncodeDelimiters 0x400000 | 0x800000 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 () 或 toEncoded ().
QUrl::EncodeReserved 0x1000000 Leave US-ASCII characters not permitted in the URL by the specification in their encoded form. This is the default on toString () 和 toEncoded ().
QUrl::DecodeReserved 0x2000000 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.
QUrl::FullyEncoded EncodeSpaces | EncodeUnicode | EncodeDelimiters | EncodeReserved 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 ()
QUrl::FullyDecoded FullyEncoded | DecodeReserved | 0x4000000 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.

完全解码

The FullyDecoded mode is similar to the behavior of the functions returning QString in Qt 4.x, in that every character represents itself and never has any special meaning. This is true even for the percent character ('%'), which should be interpreted to mean a literal percent, not the beginning of a percent-encoded sequence. The same actual character, in all other decoding modes, is represented by the sequence "%25".

Whenever re-applying data obtained with QUrl::FullyDecoded into a QUrl , care must be taken to use the QUrl::DecodedMode parameter to the setters (like setPath () 和 setUserName ()). Failure to do so may cause re-interpretation of the percent character ('%') as the beginning of a percent-encoded sequence.

This mode is quite useful when portions of a URL are used in a non-URL context. For example, to extract the username, password or file paths in an FTP client application, the FullyDecoded mode should be used.

This mode should be used with care, since there are two conditions that cannot be reliably represented in the returned QString . They are:

  • 非 UTF8 序列: URLs may contain sequences of percent-encoded characters that do not form valid UTF-8 sequences. Since URLs need to be decoded using UTF-8, any decoder failure will result in the QString containing one or more replacement characters where the sequence existed.
  • 编码定界符: URLs are also allowed to make a distinction between a delimiter found in its literal form and its equivalent in percent-encoded form. This is most commonly found in the query, but is permitted in most parts of the URL.

The following example illustrates the problem:

    QUrl original("http://example.com/?q=a%2B%3Db%26c");
    QUrl copy(original);
    copy.setQuery(copy.query(QUrl::FullyDecoded), QUrl::DecodedMode);
    qDebug() << original.toString();   // prints: http://example.com/?q=a%2B%3Db%26c
    qDebug() << copy.toString();       // prints: http://example.com/?q=a+=b&c
					

If the two URLs were used via HTTP GET, the interpretation by the web server would probably be different. In the first case, it would interpret as one parameter, with a key of "q" and value "a+=b&c". In the second case, it would probably interpret as two parameters, one with a key of "q" and value "a =b", and the second with a key "c" and no value.

该枚举在 Qt 5.0 引入或被修改。

The ComponentFormattingOptions type is a typedef for QFlags <ComponentFormattingOption>. It stores an OR combination of ComponentFormattingOption values.

另请参阅 QUrl::FormattingOptions .

enum QUrl:: ParsingMode

The parsing mode controls the way QUrl 剖析字符串。

常量 描述
QUrl::TolerantMode 0 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.
QUrl::StrictMode 1 Only valid URLs are accepted. This mode is useful for general URL validation.
QUrl::DecodedMode 2 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 QUrl::FullyDecoded .

In TolerantMode, the parser has the following behaviour:

  • Spaces and "%20": unencoded space characters will be accepted and will be treated as equivalent to "%20".
  • Single "%" characters: Any occurrences of a percent character "%" not followed by exactly two hexadecimal characters (e.g., "13% coverage.html") will be replaced by "%25". Note that one lone "%" character will trigger the correction mode for all percent characters.
  • Reserved and unreserved characters: An encoded URL should only contain a few characters as literals; all other characters should be percent-encoded. In TolerantMode, these characters will be accepted if they are found in the URL: space / double-quote / "<" / ">" / "" / "^" / "`" / "{" / "|" / "}" Those same characters can be decoded again by passing QUrl::DecodeReserved to toString () 或 toEncoded (). In the getters of individual components, those characters are often returned in decoded form.

When in StrictMode, if a parsing error is found, isValid () 会返回 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 ().

另请参阅 fromUserInput (), setUrl (), toString (), toEncoded (),和 QUrl::FormattingOptions .

enum QUrl:: UrlFormattingOption
flags QUrl:: FormattingOptions

格式化选项定义 URL 是如何被格式的,当以文本写出时。

常量 描述
QUrl::None 0x0 The format of the URL is unchanged.
QUrl::RemoveScheme 0x1 The scheme is removed from the URL.
QUrl::RemovePassword 0x2 Any password in the URL is removed.
QUrl::RemoveUserInfo RemovePassword | 0x4 Any user information in the URL is removed.
QUrl::RemovePort 0x8 Any specified port is removed from the URL.
QUrl::RemoveAuthority RemoveUserInfo | RemovePort | 0x10
QUrl::RemovePath 0x20 The URL's path is removed, leaving only the scheme, host address, and port (if present).
QUrl::RemoveQuery 0x40 The query part of the URL (following a '?' character) is removed.
QUrl::RemoveFragment 0x80
QUrl::RemoveFilename 0x800 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.
QUrl::PreferLocalFile 0x200 If the URL is a local file according to isLocalFile () and contains no query or fragment, a local file path is returned.
QUrl::StripTrailingSlash 0x400 The trailing slash is removed from the path, if one is present.
QUrl::NormalizePathSegments 0x1000 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 Nameprep , which QUrl conforms to, require host names to always be converted to lower case, regardless of the Qt::FormattingOptions used.

选项来自 QUrl::ComponentFormattingOptions are also possible.

The FormattingOptions type is a typedef for QFlags <UrlFormattingOption>. It stores an OR combination of UrlFormattingOption values.

另请参阅 QUrl::ComponentFormattingOptions .

enum QUrl:: UserInputResolutionOption
flags QUrl:: UserInputResolutionOptions

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 .

常量 描述
QUrl::DefaultResolution 0 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.
QUrl::AssumeLocalFile 1 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.

该枚举在 Qt 5.4 引入或被修改。

The UserInputResolutionOptions type is a typedef for QFlags <UserInputResolutionOption>. It stores an OR combination of UserInputResolutionOption values.

另请参阅 fromUserInput ().

成员函数文档编制

QUrl:: QUrl ( QUrl && other )

移动构造 QUrl 实例,使之指向同一对象如 other 所指向的。

该函数在 Qt 5.2 引入。

QUrl:: QUrl (const QString & url , QUrl::ParsingMode parsingMode = TolerantMode)

构造 URL 通过剖析 url 。QUrl 将自动 % (百分号) 编码不允许在 URL 中的所有字符,并解码表示无保留字符 (字母、数字、连字符、下划线、点及波浪号) 的百分号编码序列。所有其它字符留在它们的原始形式。

剖析 url 使用剖析模式 parsingMode 。在 TolerantMode (默认),QUrl 将纠正某些差错,显而易见的 % (百分号) 字符后未跟 2 十六进制数字,且它将接受任何位置的任何字符。在 StrictMode ,编码差错不会被容忍且 QUrl 还会校验某些被禁止字符是否以未编码形式呈现。若检测到错误在 StrictMode , isValid () 将返回 false。剖析模式 DecodedMode 在此上下文中不准许。

范例:

QUrl url("http://www.example.com/List of holidays.xml");
// url.toEncoded() == "http://www.example.com/List%20of%20holidays.xml"
					

要从编码字符串构造 URL,还可以使用 fromEncoded ():

QUrl url = QUrl::fromEncoded("http://qt-project.org/List%20of%20holidays.xml");
					

这 2 函数是等效的且在 Qt 5 中,2 函数均接受编码数据。通常,选取 QUrl 构造函数或 setUrl () vs fromEncoded () 将从属源数据:构造函数和 setUrl () take a QString ,而 fromEncoded 接受 QByteArray .

另请参阅 setUrl (), fromEncoded (),和 TolerantMode .

QUrl:: QUrl (const QUrl & other )

构造副本为 other .

QUrl:: QUrl ()

构造空的 QUrl 对象。

QUrl &QUrl:: operator= ( QUrl && other )

移动赋值 other 到此 QUrl 实例。

该函数在 Qt 5.2 引入。

QUrl &QUrl:: operator= (const QString & url )

赋值指定 url 到此对象。

QUrl &QUrl:: operator= (const QUrl & url )

赋值指定 url 到此对象。

QUrl:: ~QUrl ()

析构函数;立即调用在对象被删除之前。

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 .

这始终相当于 QUrl (url. toString (options)).

该函数在 Qt 5.2 引入。

另请参阅 FormattingOptions , toEncoded (),和 toString ().

QString QUrl:: authority ( QUrl::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 () 和 port () 单独。

另请参阅 setAuthority (), userInfo (), userName (), password (), host (),和 port ().

void QUrl:: clear ()

重置内容为 QUrl 。在调用此函数后, QUrl 等于采用默认空构造函数构造的。

另请参阅 isEmpty ().

QString QUrl:: errorString () const

返回错误消息,若最后操作修改此 QUrl 对象遇到剖析错误。若未检测到错误,此函数返回空字符串和 isValid () 返回 true .

由此函数返回的错误消息本质上是技术性的,最终用户可能不理解。对于开发人员最有用的是试着理解为什么 QUrl 不接受某些输入。

该函数在 Qt 4.2 引入。

另请参阅 QUrl::ParsingMode .

QString QUrl:: fileName ( QUrl::ComponentFormattingOptions options = FullyDecoded) const

返回文件名,排除目录路径。

注意,若此 QUrl 给定以斜杠结尾的路径,认为文件名是空的。

若路径不包含任何斜杠,将其作为 fileName (文件名) 完整返回。

范例:

QUrl url("http://qt-project.org/support/file.html");
// url.adjusted(RemoveFilename) == "http://qt-project.org/support/"
// url.fileName() == "file.html"
					

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 .

该函数在 Qt 5.2 引入。

另请参阅 path ().

QString QUrl:: fragment ( QUrl::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 .

注意, 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.

另请参阅 setFragment () 和 hasFragment ().

[static] QString QUrl:: fromAce (const QByteArray & domain )

Returns the Unicode form of the given domain name domain , which is encoded in the ASCII Compatible Encoding (ACE). 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. It is part of the Internationalizing Domain Names in Applications (IDNA) specification, which allows for domain names (like "example.com" ) to be written using international characters.

该函数在 Qt 4.2 引入。

[static] QUrl QUrl:: fromCFURL ( CFURLRef url )

构造 QUrl containing a copy of the CFURL url .

该函数在 Qt 5.2 引入。

[static] QUrl QUrl:: fromEncoded (const QByteArray & input , QUrl::ParsingMode parsingMode = TolerantMode)

剖析 input and returns the corresponding QUrl . input is assumed to be in encoded form, containing only ASCII characters.

Parses the URL using parsingMode 。见 setUrl () for more information on this parameter. QUrl::DecodedMode 在此上下文中不准许。

另请参阅 toEncoded () 和 setUrl ().

[static] QUrl QUrl:: fromLocalFile (const QString & localFile )

返回 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 ().

localFile leads to an empty URL (since Qt 5.4).

    qDebug() << QUrl::fromLocalFile("file.txt");            // QUrl("file:file.txt")
    qDebug() << QUrl::fromLocalFile("/home/user/file.txt"); // QUrl("file:///home/user/file.txt")
    qDebug() << QUrl::fromLocalFile("file:file.txt");       // doesn't make sense; expects path, not url with scheme
					

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:

    QUrl url = QUrl::fromLocalFile("file.txt");
    QUrl baseUrl = QUrl("file:/home/user/");
    // wrong: prints QUrl("file:file.txt"), as url already has a scheme
    qDebug() << baseUrl.resolved(url);
					

To resolve such a URL, it's necessary to remove the scheme beforehand:

    // correct: prints QUrl("file:///home/user/file.txt")
    url.setScheme(QString());
    qDebug() << baseUrl.resolved(url);
					

For this reason, it is better to use a relative URL (that is, no scheme) for relative file paths:

    QUrl url = QUrl("file.txt");
    QUrl baseUrl = QUrl("file:/home/user/");
    // prints QUrl("file:///home/user/file.txt")
    qDebug() << baseUrl.resolved(url);
					

另请参阅 toLocalFile (), isLocalFile (),和 QDir::toNativeSeparators ().

[static] QUrl QUrl:: fromNSURL (const NSURL * url )

构造 QUrl 包含 NSURL 的拷贝为 url .

该函数在 Qt 5.2 引入。

[static] QString QUrl:: fromPercentEncoding (const QByteArray & input )

返回的解码拷贝源于 input . input 首先从百分比编码解码,然后从 UTF-8 转换成 Unicode。

注意: 给定无效输入 (譬如:包含 %G5 序列的字符串,不是有效十六进制数字),输出也将无效。例如:%G5 序列可以解码为 W。

[static] QList < QUrl > QUrl:: fromStringList (const QStringList & urls , QUrl::ParsingMode mode = TolerantMode)

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.

该函数在 Qt 5.1 引入。

[static] QUrl QUrl:: fromUserInput (const QString & userInput )

返回有效 URL 从用户供给的 userInput 字符串若可以被扣除。在不可能的情况下,无效 QUrl () 被返回。

大多数可以浏览 Web 的应用程序都允许用户以纯字符串形式输入 URL。此字符串可以被手动键入位置栏,从剪贴板获得,或通过命令行自变量传入。

当字符串不是有效 URL 时,履行最佳猜测做出各种 Web 相关假定。

若字符串对应系统中的有效文件路径,构造 file:// URL 使用 QUrl::fromLocalFile ().

若不是这种情况,试图把字符串转换成 http:// 或 ftp:// URL。为后者若字符串以 ftp 开头。然后传递结果透过 QUrl 的容忍剖析器,若成功,有效 QUrl 被返回,否则返回 QUrl ().

范例:

  • qt-project.org 变为 http://qt-project.org
  • ftp.qt-project.org 变为 ftp://ftp.qt-project.org
  • hostname 变为 http://hostname
  • /home/user/test.html 变为 file:///home/user/test.html

该函数在 Qt 4.6 引入。

[static] QUrl QUrl:: fromUserInput (const QString & userInput , const QString & workingDirectory , QUrl::UserInputResolutionOptions options = DefaultResolution)

返回有效 URL 从用户供给的 userInput 字符串若可以被扣除。在不可能的情况下,无效 QUrl () 被返回。

这重载接受 workingDirectory 路径,为了能够处理相对路径。这特别有用当处理命令行自变量时。若 workingDirectory 为空,不会做相对路径处理,因此,此方法的行为像重载其某一自变量。

默认情况下,输入字符串才会看起来像要被这样对待的相对路径若文件实际存在于给定工作目录下时。

若应用程序可以处理尚不存在的文件,应该传递标志 AssumeLocalFile in options .

该函数在 Qt 5.4 引入。

bool QUrl:: hasFragment () const

返回 true 若此 URL 包含片段 (即:若看到 # 位于其中)。

该函数在 Qt 4.2 引入。

另请参阅 fragment () 和 setFragment ().

bool QUrl:: hasQuery () const

返回 true 若此 URL 包含 Query (即:若看到 ? 位于其中)。

该函数在 Qt 4.2 引入。

另请参阅 setQuery (), query (),和 hasFragment ().

QString QUrl:: host ( QUrl::ComponentFormattingOptions options = FullyDecoded) const

返回 URL 的主机若 URL 有定义;否则返回空字符串。

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.

另请参阅 setHost (), idnWhitelist (), setIdnWhitelist (),和 authority ().

[static] QStringList QUrl:: idnWhitelist ()

返回顶级域名的当前白名单,这些域名的组合中允许有非 ASCII 字符。

setIdnWhitelist () 了解此列表的基本原理。

该函数在 Qt 4.2 引入。

另请参阅 setIdnWhitelist ().

bool QUrl:: isEmpty () const

返回 true 若 URL 没有数据;否则返回 false .

另请参阅 clear ().

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 ().

该函数在 Qt 4.8 引入。

另请参阅 fromLocalFile () 和 toLocalFile ().

bool QUrl:: isParentOf (const QUrl & childUrl ) const

返回 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 .

bool QUrl:: isRelative () const

返回 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.

另请参阅 相对 URL vs 相对路径 .

bool QUrl:: isValid () const

返回 true 若 URL 非空且有效;否则返回 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.

bool checkUrl(const QUrl &url) {
    if (!url.isValid()) {
        qDebug("Invalid URL: %s", qUtf8Printable(url.toString()));
        return false;
    }
    return true;
}
					

bool QUrl:: 匹配 (const QUrl & url , QUrl::FormattingOptions options ) const

返回 true 若此 URL 和给定 url 相等后于应用 options 到两者;否则返回 false .

This is equivalent to calling adjusted(options) on both URLs and comparing the resulting urls, but faster.

该函数在 Qt 5.2 引入。

QString QUrl:: password ( QUrl::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 .

注意, 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.

另请参阅 setPassword ().

QString QUrl:: path ( QUrl::ComponentFormattingOptions options = FullyDecoded) const

返回 URL 路径。

    qDebug() << QUrl("file:file.txt").path();                   // "file.txt"
    qDebug() << QUrl("/home/user/file.txt").path();             // "/home/user/file.txt"
    qDebug() << QUrl("http://www.example.com/test/123").path(); // "/test/123"
					

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 .

注意, 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 (默认):

    qDebug() << QUrl("/foo%FFbar").path();
					

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 + ):

    qDebug() << QUrl("/foo+bar%2B").path(); // "/foo+bar+"
					

Other decoding examples:

    const QUrl url("/tmp/Mambo %235%3F.mp3");
    qDebug() << url.path(QUrl::FullyDecoded);  // "/tmp/Mambo #5?.mp3"
    qDebug() << url.path(QUrl::PrettyDecoded); // "/tmp/Mambo #5?.mp3"
    qDebug() << url.path(QUrl::FullyEncoded);  // "/tmp/Mambo%20%235%3F.mp3"
					

另请参阅 setPath ().

int QUrl:: port ( int defaultPort = -1) const

返回 URL 端口,或 defaultPort 若端口未指定。

范例:

QTcpSocket sock;
sock.connectToHost(url.host(), url.port(80));
					

该函数在 Qt 4.1 引入。

另请参阅 setPort ().

QString QUrl:: query ( QUrl::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 ('+').

另请参阅 setQuery () 和 hasQuery ().

QUrl QUrl:: resolved (const QUrl & relative ) const

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.

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:

QUrl baseUrl("http://qt.digia.com/Support/");
QUrl relativeUrl("../Product/Library/");
qDebug(baseUrl.resolved(relativeUrl).toString());
// prints "http://qt.digia.com/Product/Library/"
					

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 "/".

另请参阅 isRelative ().

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.

另请参阅 setScheme () 和 isRelative ().

void QUrl:: setAuthority (const QString & authority , QUrl::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.

此函数不允许 mode QUrl::DecodedMode 。要设置完全解码的数据,调用 setUserName (), setPassword (), setHost () 和 setPort () 单独。

另请参阅 authority (), setUserInfo (), setHost (),和 setPort ().

void QUrl:: setFragment (const QString & fragment , QUrl::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 () 采用 QUrl::FullyDecoded 格式化选项。

另请参阅 fragment () 和 hasFragment ().

void QUrl:: setHost (const QString & host , QUrl::ParsingMode mode = DecodedMode)

将 URL 的主机设为 host 。主机是授权的一部分。

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.

另请参阅 host () 和 setAuthority ().

[static] void QUrl:: setIdnWhitelist (const QStringList & list )

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.

该函数在 Qt 4.2 引入。

另请参阅 idnWhitelist ().

void QUrl:: setPassword (const QString & password , QUrl::ParsingMode mode = DecodedMode)

将 URL 口令设为 password 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 () 采用 QUrl::FullyDecoded 格式化选项。

另请参阅 password () 和 setUserInfo ().

void QUrl:: setPath (const QString & path , QUrl::ParsingMode mode = DecodedMode)

将 URL 路径设为 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 () 采用 QUrl::FullyDecoded 格式化选项。

另请参阅 path ().

void QUrl:: setPort ( int port )

将 URL 端口设为 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.

另请参阅 port ().

void QUrl:: setQuery (const QString & query , QUrl::ParsingMode mode = TolerantMode)

将 URL 查询字符串设为 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 .

另请参阅 query () 和 hasQuery ().

void QUrl:: setQuery (const QUrlQuery & query )

这是重载函数。

将 URL 查询字符串设为 query .

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.

该函数在 Qt 5.0 引入。

另请参阅 query () 和 hasQuery ().

void QUrl:: setScheme (const QString & scheme )

将 URL 方案设为 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 RFC 3986 兼容: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )

The following example shows a URL where the scheme is "ftp":

To set the scheme, the following call is used:

    QUrl url;
    url.setScheme("ftp");
					

The scheme can also be empty, in which case the URL is interpreted as relative.

另请参阅 scheme () 和 isRelative ().

void QUrl:: setUrl (const QString & url , QUrl::ParsingMode parsingMode = TolerantMode)

剖析 url 并将此对象设为该值。 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, undercores, dots and tildes). All other characters are left in their original forms.

剖析 url 使用剖析模式 parsingMode 。在 TolerantMode (默认), 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 () 将返回 false。剖析模式 DecodedMode is not permitted in this context and will produce a run-time warning.

另请参阅 url () 和 toString ().

void QUrl:: setUserInfo (const QString & userInfo , QUrl::ParsingMode mode = TolerantMode)

将 URL 用户信息设为 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.

此函数不允许 mode QUrl::DecodedMode 。要设置完全解码的数据,调用 setUserName () 和 setPassword () 单独。

另请参阅 userInfo (), setUserName (), setPassword (),和 setAuthority ().

void QUrl:: setUserName (const QString & userName , QUrl::ParsingMode mode = DecodedMode)

将 URL 的用户名设为 userName 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 () 采用 QUrl::FullyDecoded 格式化选项。

另请参阅 userName () 和 setUserInfo ().

void QUrl:: swap ( QUrl & other )

交换 URL other 与此 URL。此操作非常快且从不失败。

该函数在 Qt 4.8 引入。

[static] QByteArray QUrl:: toAce (const QString & domain )

Returns the ASCII Compatible Encoding of the given domain name domain . 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. It is part of the Internationalizing Domain Names in Applications (IDNA) specification, which allows for domain names (like "example.com" ) to be written using international characters.

此函数返回空 QByteArray if domain is not a valid hostname. Note, in particular, that IPv6 literals are not valid domain names.

该函数在 Qt 4.2 引入。

CFURLRef QUrl:: toCFURL () const

创建 CFURL 从 QUrl . The caller owns the CFURL and is responsible for releasing it.

该函数在 Qt 5.2 引入。

QString QUrl:: toDisplayString ( QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const

Returns a human-displayable string representation of the URL. The output can be customized by passing flags with options 。选项 RemovePassword is always enabled, since passwords should never be shown back to users.

采用默认选项,结果 QString 可以传回 QUrl 稍后,但最初存在的任何口令会丢失。

该函数在 Qt 5.0 引入。

另请参阅 FormattingOptions , toEncoded (),和 toString ().

QByteArray QUrl:: toEncoded ( QUrl::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.

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").

    qDebug() << QUrl("file:file.txt").toLocalFile();            // "file.txt"
    qDebug() << QUrl("file:/home/user/file.txt").toLocalFile(); // "/home/user/file.txt"
    qDebug() << QUrl("file.txt").toLocalFile();                 // ""; wasn't a local file as it had no scheme
					

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.

另请参阅 fromLocalFile () 和 isLocalFile ().

NSURL *QUrl:: toNSURL () const

创建 NSURL 从 QUrl 。NSURL 被自动释放。

该函数在 Qt 5.2 引入。

[static] QByteArray QUrl:: toPercentEncoding (const QString & input , const QByteArray & exclude = QByteArray(), const QByteArray & 包括 = QByteArray())

返回编码副本为 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 包括 .

无预留定义为: ALPHA / DIGIT / "-" / "." / "_" / "~"

QByteArray ba = QUrl::toPercentEncoding("{a fishy string?}", "{}", "s");
qDebug(ba.constData());
// prints "{a fi%73hy %73tring%3F}"
					

QString QUrl:: toString ( QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const

返回 URL 的字符串表示。可以定制输出,通过传递标志采用 options 。选项 QUrl::FullyDecoded is not permitted in this function since it would generate ambiguous data.

默认格式化选项为 PrettyDecoded .

另请参阅 FormattingOptions , url (),和 setUrl ().

[static] QStringList QUrl:: toStringList (const QList < QUrl > & urls , QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded))

转换列表 urls 成列表 QString 对象,使用 toString ( options ).

该函数在 Qt 5.1 引入。

QString QUrl:: url ( QUrl::FormattingOptions options = FormattingOptions(PrettyDecoded)) const

返回 URL 的字符串表示。可以定制输出,通过传递标志采用 options 。选项 QUrl::FullyDecoded is not permitted in this function since it would generate ambiguous data.

结果 QString 可以传回 QUrl later on.

同义词 toString (options).

另请参阅 setUrl (), FormattingOptions , toEncoded (),和 toString ().

QString QUrl:: userInfo ( QUrl::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 () 和 password () 单独。

另请参阅 setUserInfo (), userName (), password (),和 authority ().

QString QUrl:: userName ( QUrl::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 .

注意, 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.

另请参阅 setUserName () 和 userInfo ().

bool QUrl:: operator!= (const QUrl & url ) const

返回 true 若此 URL 和给定 url 不相等;则返回 false .

另请参阅 匹配 ().

bool QUrl:: operator== (const QUrl & url ) const

返回 true 若此 URL 和给定 url 相等;否则返回 false .

另请参阅 匹配 ().

相关非成员

QDataStream & operator<< ( QDataStream & out , const QUrl & url )

写入 URL url 到流 out 并返回流引用。

另请参阅 QDataStream 运算符格式 .

QDataStream & operator>> ( QDataStream & in , QUrl & url )

将 URL 读入 url 从流 in 并返回流引用。

另请参阅 QDataStream 运算符格式 .

宏文档编制

QT_NO_URL_CAST_FROM_STRING

禁用自动转换从 QString (或 char *) 到 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 转换。

例如,若有代码像

url = filename; // probably not what you want
					

可以把它重写成

url = QUrl::fromLocalFile(filename);
url = baseurl.resolved(QUrl(filename));
					

另请参阅 QT_NO_CAST_FROM_ASCII .