mort
mort

Reputation: 13588

Best way to convert std::wstring to QString

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.

Upvotes: 22

Views: 21633

Answers (3)

borisbn
borisbn

Reputation: 5054

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

Upvotes: 25

Tony The Lion
Tony The Lion

Reputation: 63190

I think a user defined conversion is what you're looking for, and from what I can gather, it should look something like this:

class foo
{
public:
   operator QString(std::wstring& ws)
   {
       return QString::fromStdWString(ws);
   }
}

Upvotes: 2

Zaiborg
Zaiborg

Reputation: 2522

maybe make a inline function QString toQString(std::wstring string) to make it 'less to type' ...

but to be honest ... thats not the big effort at all to write it from time to time ;)

soo long zai

Upvotes: 0

Related Questions