12

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

NOTES: this code is from wkhtmltopdf and postData is a QByteArray.

However, Qt 5 does not have the addQueryItem() function anymore. How do you port this code?

waddlesplash
  • 743
  • 1
  • 6
  • 25

1 Answers1

21

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

This means that QUrlQuery will only be #included 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

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: In the case you want to use a real QUrl that has a URL portion, add this:

 QUrl url;
 url.setQuery(q);
waddlesplash
  • 743
  • 1
  • 6
  • 25
  • How does this change if `url` already has a partial query that I'd like to add to? I don't see a way to append to the existing query in a `QUrl`. – Phlucious Jul 27 '18 at 23:56
  • I realized right after I posted that you can initialize the `QUrlQuery` with the existing url to avoid overwriting existing queries, like this: `QUrlQuery q(url); q.addQuery(…); url.setQuery(q);` – Phlucious Jul 28 '18 at 00:01