你如何将 QUrl addQueryItem 移植到 Qt5 的 QUrlQuery? [英] How do you port QUrl addQueryItem to Qt5's QUrlQuery?
问题描述
在Qt
4中,使用QUrl
的以下代码有效:
In Qt
4, the following code using QUrl
works:
QUrl u;
foreach (const settings::PostItem & pi, settings.post)
u.addQueryItem(pi.name, pi.value);
postData = u.encodedQuery();
注意:此代码来自 wkhtmltopdf 和 postData
是一个 QByteArray.
NOTES: this code is from wkhtmltopdf and postData
is a QByteArray.
然而,Qt
5 不再有 addQueryItem()
函数.你如何移植这个代码?
However, Qt
5 does not have the addQueryItem()
function anymore. How do you port this code?
推荐答案
为了确保与 Qt
4 兼容,请在文件顶部添加以下几行:
In order to ensure compatibility with Qt
4, add the following lines at the top of your file:
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
# include <QUrlQuery>
#endif
这意味着如果您针对 Qt
5.0.0 或更高版本进行编译,QUrlQuery
只会被 #include
d.
This means that QUrlQuery
will only be #include
d if you are compiling against Qt
5.0.0 or greater.
然后在问题中指定的代码上方添加以下行:
Then add the following line above the code specified in the question:
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
然后在问题中指定的代码下方插入此代码:
and then insert this code below the code specified in the question:
#else
QUrlQuery q;
foreach (const settings::PostItem & pi, settings.post)
q.addQueryItem(pi.name, pi.value);
postData = q.query(QUrl::FullyEncoded).toUtf8();
#endif
注意:使用 toUtf8()
是因为 postData
是 QByteArray
和 query()
返回一个 QString
.toAscii()
在 Qt
5 中已被弃用,但 UTF-8 是 ASCII 的子集,仅在必要时使用 Unicode 字符.
NOTE: toUtf8()
is used because postData
is a QByteArray
and query()
returns a QString
. toAscii()
was deprecated in Qt
5, but UTF-8 is a subset of ASCII with Unicode characters only when necessary.
EDIT:如果您想使用具有 URL 部分的真实 QUrl
,请添加:
EDIT: In the case you want to use a real QUrl
that has a URL portion, add this:
QUrl url;
url.setQuery(q);
这篇关于你如何将 QUrl addQueryItem 移植到 Qt5 的 QUrlQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!