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 | matches (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 要求)。
調用 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 認為是有效的,即使它們沒有意義 (當使用時):
當剖析器遇到錯誤時,它信號事件通過使 isValid () 返迴 false 和 toString () / toEncoded () 返迴空字符串。若有必要嚮用戶展示 URL 剖析為什麼失敗的原因,可以從 QUrl 獲得錯誤條件通過調用 errorString ()。注意:此消息是高度技術性的,且對最終用戶可能沒有意義。
QUrl 隻能記錄一種錯誤條件。若發現多個錯誤,則不確定要報告哪個錯誤。
遵循這些規則以避免錯誤字符轉換,當處理 URL 和字符串時:
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:
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 .
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:
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 .
格式化選項定義 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 .
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 實例,使之指嚮同一對象如 other 所指嚮的。
該函數在 Qt 5.2 引入。
構造 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 .
構造副本為 other .
構造空的 QUrl 對象。
移動賦值 other 到此 QUrl 實例。
該函數在 Qt 5.2 引入。
賦值指定 url 到此對象。
賦值指定 url 到此對象。
析構函數;立即調用在對象被刪除之前。
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 ().
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 ().
重置內容為 QUrl 。在調用此函數後, QUrl 等於采用默認空構造函數構造的。
另請參閱 isEmpty ().
返迴錯誤消息,若最後操作修改此
QUrl
對象遇到剖析錯誤。若未檢測到錯誤,此函數返迴空字符串和
isValid
() 返迴
true
.
由此函數返迴的錯誤消息本質上是技術性的,最終用戶可能不理解。對於開發人員最有用的是試著理解為什麼 QUrl 不接受某些輸入。
該函數在 Qt 4.2 引入。
另請參閱 QUrl::ParsingMode .
返迴文件名,排除目錄路徑。
注意,若此 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 ().
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 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 引入。
返迴
true
若此 URL 包含片段 (即:若看到 # 位於其中)。
該函數在 Qt 4.2 引入。
另請參閱 fragment () 和 setFragment ().
返迴
true
若此 URL 包含 Query (即:若看到 ? 位於其中)。
該函數在 Qt 4.2 引入。
另請參閱 setQuery (), query (),和 hasFragment ().
返迴 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 ().
返迴
true
若 URL 沒有數據;否則返迴
false
.
另請參閱 clear ().
返迴
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 ().
返迴
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
.
返迴
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 相對路徑 .
返迴
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; }
返迴
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 引入。
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 ().
返迴 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 ().
返迴 URL 端口,或 defaultPort 若端口未指定。
範例:
QTcpSocket sock; sock.connectToHost(url.host(), url.port(80));
該函數在 Qt 4.1 引入。
另請參閱 setPort ().
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 ().
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 ().
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 ().
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 ().
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 ().
將 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 ().
將 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 ().
將 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 ().
將 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 ().
將 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 .
這是重載函數。
將 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 引入。
將 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 ().
剖析 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 用戶信息設為 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 ().
將 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 ().
交換 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 引入。
創建 CFURL 從 QUrl . The caller owns the CFURL and is responsible for releasing it.
該函數在 Qt 5.2 引入。
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 ().
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.
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 。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}"
返迴 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 引入。
返迴 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 ().
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 ().
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 ().
返迴
true
若此 URL 和給定
url
不相等;則返迴
false
.
另請參閱 matches ().
返迴
true
若此 URL 和給定
url
相等;否則返迴
false
.
另請參閱 matches ().
寫入 URL url 到流 out 並返迴流引用。
另請參閱 QDataStream 運算符格式 .
將 URL 讀入 url 從流 in 並返迴流引用。
另請參閱 QDataStream 運算符格式 .
禁用自動轉換從 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 .