Convertir std:: string a QString


Tengo un std::string content que sé que contiene datos UTF-8. Quiero convertirlo en un QString. ¿Cómo hago eso, evitando la conversión from-ASCII en Qt?

Author: leyyin, 2010-12-02

3 answers

Hay una función QString llamada fromUtf8 eso toma un const char*:

QString str = QString::fromUtf8(content.c_str());
 72
Author: Michael Mrozek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-02 08:35:03

QString::fromStdString(content) es mejor ya que es más robusto. También tenga en cuenta que si std::string está codificado en UTF-8, entonces debería dar exactamente el mismo resultado que QString::fromUtf8(content.data(), int(content.size())).

 63
Author: Jackpap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-13 09:33:58

Generalmente, la mejor manera de hacer la conversión es usando el método fromUtf8, pero el problema es cuando tiene cadenas dependientes de la configuración regional.

En estos casos, es preferible usar fromLocal8Bit. Ejemplo:

std::string str = "ëxample";
QString qs = QString::fromLocal8Bit(str.c_str());
 5
Author: Tarod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-02 12:34:40