02 QT与C++字符串编码转换

1.QT字符编码格式判断

//判断字符串编码格式为GBK还是UTF-8
QString GetCorrectUnicode(const QByteArray &ba)
{
    
    
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    //调用utf8转unicode的方式转码,获取无效字符
    QString text = codec->toUnicode( ba.constData(), 1, &state);

    qDebug() <<state.invalidChars;
    //存在无效字符则是GBK,转码后返回
    if (state.invalidChars)
    {
    
    
        text = QTextCodec::codecForName( "GBK" )->toUnicode(ba);
    }
    else
    {
    
    
        text =  codec->toUnicode(ba);
    }
    return text;
}

2.QString与std::string转换

//QString转换为std::string
std::string qstrToStr(const QString qstr)
{
    
    
	QByteArray data = qstr.toLocal8Bit();
    return std::string(data);
}
//为std::string转换QString
QString strToQstr(const std::string str)
{
    
    
    return QString::fromLocal8Local(str.data());
}

猜你喜欢

转载自blog.csdn.net/pointerz_zyz/article/details/128855568