Take the 2-minute tour ×

Been doing quite a lot of work with Qt and it just hit me, which one should I use to convert my QStrings to QByteArray and back? And there is some other issues where I dont know what to do exactly.

For example when dealing with QUrl. I have an object where on of the members are a QString and I'm setting it like this:


The toEncoded() converts it to utf8 and and all non-ASCII characters are then percent encode. When I then set the QString to a QByteArray it automatically converts it Ascii.

Also, when doing most of my converting from QString to QByteArray I currently use toUtf8().

My question is, what should I use when converting from QString to QByteArray and vice versa?

share|improve this question
You don't say what you intend to use this QByteArray for, or what kind of strings you intend to store in it. –  Nicol Bolas Apr 17 '12 at 1:01
the qbytearray is needed when dealing with some libraries and some functions that wants a char array. using QString –  chikuba Apr 17 '12 at 1:07
OK, then what do those libraries and functions accept? Do they expect UTF-8, or do they only take ASCII? Or do they take something else entirely, like Latin-1 and such? –  Nicol Bolas Apr 17 '12 at 1:07
actaully have no idea to be honest. im using utf8 for the base64 encoding lib atm and the key that im generating seems to work –  chikuba Apr 17 '12 at 1:22
Base64 uses ASCII. Granted, any ASCII string is also UTF8, so it doesn't really matter. –  Nicol Bolas Apr 17 '12 at 2:10

2 Answers 2

up vote 1 down vote accepted

If there is a chance that you are going to use non-english characters it's better to use UTF-8. It's standard and good practice to use it because you never know who might be reusing your code in the future.

share|improve this answer
so should i change how QString() converts QBYteArray? –  chikuba Apr 16 '12 at 23:08
I'm not QT expert. You wrote, you were using toUtf8() doing conversion. I understand you already use UTF8. So my piece of advice is keep doing it. –  shark555 Apr 16 '12 at 23:16
If you're worried about implicit conversions, I'd suggest to define QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to disable them alltogether. And then use toUtf8/fromUtf8,QLatin1String() etc. to explicitely convert. –  Frank Osterfeld Apr 17 '12 at 7:31

UTF-8 and ASCII are usually exactly the same thing when dealing with English characters. The difference is that if you ever use non-English characters UTF-8 will be able to support it while ASCII won't. I suggest using UTF-8 just to play it safe.

share|improve this answer
how to make QString use fromUtf8() when creating string? –  chikuba Apr 16 '12 at 23:12
newString = QString::fromUtf8(yourArray);? I don't really understand what you're asking... –  slartibartfast Apr 16 '12 at 23:17
qt-project.org/doc/qt-4.8/qstring.html#QString-9 currently use the constructor which converts it to ascii –  chikuba Apr 16 '12 at 23:21

Your Answer


