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?
            Asked
            
        
        
            Active
            
        
            Viewed 1.2e+01k times
        
    4 Answers
131
            
            
        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())).
- 
                    5Only in Qt5. In Qt4 it uses QString::fromAscii. – Rémi Benoit Mar 17 '16 at 09:12
- 
                    5This should be the accepted answer. However your last statement is not necessarily true. In the C++ standard there is no guarantee, that `std::string` is encoded in UTF8 (actually the encoding is unspecified), so `QString::fromUtf8(content.data(), int(content.size()))` may give different (and also incorrect) results than `QString::fromStdString(content)`. – plasmacel Apr 13 '18 at 09:27
106
            There's a QString function called fromUtf8 that takes a const char*:
QString str = QString::fromUtf8(content.c_str());
 
    
    
        leyyin
        
- 27
- 1
- 4
 
    
    
        Michael Mrozek
        
- 169,610
- 28
- 168
- 175
- 
                    20More efficient: `QString::fromUtf8( content.data(), content.size() )` – Marc Mutz - mmutz Apr 29 '11 at 21:22
- 
                    3In the C++ standard there is no guarantee, that `std::string` is encoded in UTF8 (actually the encoding is unspecified), so this answer is not entirely correct. At least you should check the encoding by an assertion. – plasmacel Apr 13 '18 at 09:26
13
            
            
        Since Qt5 fromStdString internally uses fromUtf8, so you can use both:
inline QString QString::fromStdString(const std::string& s) 
{
return fromUtf8(s.data(), int(s.size()));
}
 
    
    
        maxa
        
- 171
- 1
- 4
9
            
            
        Usually, the best way of doing the conversion is using the method fromUtf8, but the problem is when you have strings locale-dependent.
In these cases, it's preferable to use fromLocal8Bit. Example:
std::string str = "ëxample";
QString qs = QString::fromLocal8Bit(str.c_str());
 
    
    
        Tarod
        
- 6,732
- 5
- 44
- 50
 
     
    