QString to string Chinese garbled problem in Qt

The conversion between QString and string can be done as follows:

QString::toStdString();
QString::fromStdString();

Convert numbers and QStrings to each other:

QString::number(); //数字转QString,括号里填数字
toInt(); //QString转数字 qstring.toInt();

However, the direct conversion between QString and string will cause Chinese garbled characters. For this reason, three statements are provided in Qt4.

QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
//↑这两个函数在QT5中已被去掉
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

However, because many programmers do not consider whether these three lines of code have any side effects at all, as long as there are garbled characters, these three lines of code are used indiscriminately, resulting in abuse, so the first two functions are removed in Qt5

So how should we solve the problem of Chinese garbled characters? Of course, the answer is yes. The following two methods can be defined in the program.

QString str2qstr(const string str)
{
    return QString::fromLocal8Bit(str.data());
}

string qstr2str(const QString qstr)
{
    QByteArray cdata = qstr.toLocal8Bit();
    return string(cdata);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325953144&siteId=291194637