Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::string to QString

I've got an std::string content that I know contains UTF-8 data. I want to convert it to a QString. How do I do that, avoiding the from-ASCII conversion in Qt?

like image 387
Fred Foo Avatar asked Dec 02 '10 17:12

Fred Foo


People also ask

How do you assign a string to a QString?

std::string s = "Übernahme"; QString q = QString::fromLocal8Bit(s. c_str()); If you don't have to deal with such strings, then the above answers will work fine.

How do you convert std::string to Lpwstr?

std::wstring stemp = std::wstring(s. begin(), s. end()); LPCWSTR sw = stemp. c_str();

How do I convert a string to an int in CPP STL?

Using the stoi() function The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value. The stoi() function contains an str argument. The str string is passed inside the stoi() function to convert string data into an integer value.

How do I cast a std::string to char?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.


2 Answers

QString::fromStdString(content) is better since it is more robust. Also note, that if std::string is encoded in UTF-8, then it should give exactly the same result as QString::fromUtf8(content.data(), int(content.size())).

like image 159
Jackpap Avatar answered Sep 28 '22 02:09

Jackpap


There's a QString function called fromUtf8 that takes a const char*:

QString str = QString::fromUtf8(content.c_str()); 
like image 43
Michael Mrozek Avatar answered Sep 28 '22 01:09

Michael Mrozek