Convert std :: string to QString

I have std::string content that I know contains UTF-8 data. I want to convert it to QString . How can I do this while avoiding conversion from ASCII to Qt?

+58
c ++ string qt utf-8 qstring
Dec 02 '10 at 17:45
source share
4 answers

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

 QString str = QString::fromUtf8(content.c_str()); 
+75
Dec 02 '10 at 17:51
source share

QString::fromStdString(content) better since it is more stable. 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())) .

+65
Sep 01 '13 at 11:32
source share

Usually the best way to do the conversion is to use a method from Utf8 , but the problem is that you have locale-specific strings.

In these cases, it is preferable to use from Local8Bit . Example:

 std::string str = "Γ«xample"; QString qs = QString::fromLocal8Bit(str.c_str()); 
+5
02 Sep '15 at 12:34
source share

Since Qt5 fromStdString internally uses fromUtf8, so you can use like:

 inline QString QString::fromStdString(const std::string& s) { return fromUtf8(s.data(), int(s.size())); } 
0
Jan 15 '19 at 9:42
source share



All Articles