[Qt-interest] How to convert a LPCTSTR into a QString

Reece Dunn msclrhd at googlemail.com
Wed Jun 16 23:30:36 CEST 2010


On 16 June 2010 22:18, Matthias Pospiech <matthias.pospiech at gmx.de> wrote:
> I have a Windows Message call containing a LPCTSTR, which is defined as
>
> #ifdef UNICODE
>    typedef WCHAR TCHAR;
> #else
>    typedef CHAR TCHAR;
> #endif
> typedef const TCHAR *LPCTSTR;
>
> If I now try to convert using:
>
> void Controller::Error(LPCTSTR errorMessage)
> {
>    emit errorOccurred(QString::fromLocal8Bit(errorMessage));
> }
>
> I get the error:
> error: no matching function for call to 'QString::fromLocal8Bit(const
> TCHAR*&)'
>
> what should the solution look like?

You probably have UNICODE on. The solution is to do something like this:

QString toQString(const char *str) { return QString::fromLocal8Bit(str); }
QString toQString(const wchar_t *str) { return QString::fromWCharArray(str); }

which you can then do:

void Controller::Error(LPCTSTR errorMessage)
{
    emit errorOccurred(toQString(errorMessage));
}

This will work irrespective of whether TCHAR is CHAR (char) or WCHAR
(wchar_t or unsigned short, depending on settings) and will also work
with the LPCSTR (const char *) and LPCWSTR (const wchar_t *) types.

HTH,
- Reece




More information about the Qt-interest-old mailing list