[Qt-interest] Convert a QString to string

Thiago Macieira thiago.macieira at trolltech.com
Tue Feb 10 16:00:24 CET 2009


Em Terça-feira 10 Fevereiro 2009, às 15:05:18, Jan Ekholm escreveu:
> On Tuesday 10 February 2009, Sujan Dasmahapatra wrote:
> > How can I convert a    QString  str1 to string str2.
>
> Assuming you mean std::string it's pretty obvious if you actually look into
> the docs a bit...
>
> 	std::string QString::toStdString () const

Please be careful with that function.

std::string is not a string (in the Qt sense), but a byte array. It's closer 
to QByteArray than to QString. That means that, when you convert from QString 
to std::string, you're introducing an encoding conversion and you should, 
therefore, be very careful.

Unlike the conversions to QByteArray, QString offers no choice of encoding for 
the conversion to std::string. Your only option is the toAscii() conversion, 
which is Latin 1 by default but can be changed with 
QTextCodec::setCodecForCStrings. This is important, because it's not the 
locale conversion: you may be losing data by converting to std::string.

My recommendation is that you instead modify the rest of your code to use 
QString, as far as you can. 

If you can't, then try to use std::wstring instead: all platforms where Qt is 
supported use UTF-16 or UCS-4 for wchar_t, so there's the conversion is 
trivial and there's no loss of data.

-- 
Thiago Macieira - thiago.macieira (AT) nokia.com
  Senior Product Manager - Nokia, Qt Software
     Sandakerveien 116, NO-0402 Oslo, Norway
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090210/b80e6c37/attachment.bin 


More information about the Qt-interest-old mailing list