I'm trying to convert the following QString
:
QString nom, prenom, promo;
...
QString modelName = nom + "_" + prenom + "_" promo;
into a LPTSTR
.
So far, I've used this:
LPTSTR mm = (LPTSTR) modelName.utf16();
But the LPTSTR
returned contains only the first char of the QString
. I'v tried a lot of methods, including going through a char *
, but nothing worked.
What should I do to get the full QString into the LPTSTR?
If LPTSTR mm = "TEST CODE"
works well, then in your project the sizeof(TCHAR)==1
. The little endian memory layout of an ascii UTF16-encoded string is:
xx 00 xx 00 xx 00 xx 00 ...
That's why, with a single-byte TCHAR
, your UTF-16 string is interpreted as a single character string. The first zero byte terminates it.
There are two solutions to this problem:
To use UTF-16 TCHAR
, you need to define UNICODE
for the entire project. You can either add
DEFINES += UNICODE
to your qmake project file, or add
#define UNICODE
as the first line of your code, in every header and .cpp file.
If you really wish to use the locally encoded, byte-wide TCHAR
, then you need to obtain them as follows:
QString modelName = ...;
QByteArray modelNameLocal = modelName.toLocal8Bit();
LPTSTR mm = (LPTSTR)modelNameLocal.data();
The mm
value will remain valid as long as modelNameLocal
is in scope. You need to be careful to ensure that as long as mm
is used, the underlying byte array must exist as well.