Best way to convert std::wstring to QString

mort picture mort · Feb 6, 2013 · Viewed 15.6k times · Source

I'm currently working on a larger project, where the "logic" is implemented in standard C++ with all strings being handled with std::wstring and the UI part is implemented using Qt and thus necessarily QString (Bonus question: is this true?).

What is the best way to connect those two worlds?

I know I can use something like

std::wstring wideString;
QString qtString = QString::fromStdWString(wideString);

but I'm wondering if there is a nicer way with less typing involved. A user defined operator came to my mind, but I'm not experienced enough to tackle that on my own.

Would be glad if anyone could point me in the right direction.

Answer

borisbn picture borisbn · Feb 6, 2013

It's a good idea to use QString::fromStdWString but (!!!) if Qt was compiled with exactly the same STL headers as your project. If not - you can get a lot of fun, catching a bug.

If you don't sure that both STL headers are the same use QString::fromWCharArray:

std::wstring wideString;
QString qtString = QString::fromWCharArray( wideString.c_str() );

Update: answering to @juzzlin:
Lets imagine that Qt was build with the STL containing the following std::wstring:

class wstring { // I know, that there's no such class, but I'm shure you'll understand what I want to say
    wchar_t * m_ptr;
    size_t m_length;
    ...
};

and you have the STL containing the following std::wstring:

class wstring {
    wchar_t * m_ptr;
    wchar_t * m_the_end;
    ...
};

If you'll give your std::wstring to Qt, it will interpret m_the_end pointer as the length of the string, and

you can get a lot of fun, catching a bug