What is the most basic way to do it?
original title: "c++ - How to change string into QString?"
What is the most basic way to do it?
Mi a legalapvetőbb módja ennek?
Ez az összefoglalás a fordítás után. Ha meg szeretné tekinteni a teljes fordítást, kattintson a "fordítás" ikonra
If by string you mean
std::string
you can do it with this method:QString QString::fromStdString(const std::string & str)
If by string you mean Ascii encoded
const char *
then you can use this method:QString QString::fromAscii(const char * str, int size = -1)
If you have
const char *
encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:QString QString::fromLocal8Bit(const char * str, int size = -1)
If you have
const char *
that's UTF8 encoded then you'll need to use this method:QString QString::fromUtf8(const char * str, int size = -1)
There's also method for
const ushort *
containing UTF16 encoded string:QString QString::fromUtf16(const ushort * unicode, int size = -1)
If compiled with STL compatibility,
QString
has a static method to convert astd::string
to aQString
:Alternative way:
This has the advantage of not using
.c_str()
which might cause thestd::string
to copy itself in case there is no place to add the'\0'
at the end.Warning: This won't work if the
std::string
contains\0
s.I came across this question because I had a problem when following the answers, so I post my solution here.
The above examples all show samples with strings containing only ASCII values, in which case everything works fine. However, when dealing with strings in Windows whcih can also contain other characters, like german umlauts, then these solutions don't work
The only code that gives correct results in such cases is
If you don't have to deal with such strings, then the above answers will work fine.
Moreover, to convert whatever you want, you can use the QVariant class.
for example:
output
Do you mean a C string, as in a
char*
string, or a C++std::string
object?Either way, you use the same constructor, as documented in the QT reference:
For a regular C string, just use the main constructor:
For a
std::string
, you obtain thechar*
to the buffer and pass that to theQString
constructor: