Home  >  Q&A  >  body text

c++ - QT QSetting类读取ini文件乱码

斜体文字使用QT QSetting类 ,设置读取编码为utf8,读取ini 文件
ini文件的文件的编码设置为ASCII可以读到数据,但是中文乱码;
ini文件的文件的编码设置为UTF-8可读不到到数据。这种情况有的文件有,有的没有;但是给第一行加上一个换行就可以读到数据,但是乱码问题还是不好解决。
不知道有木有人遇到过,哪位大神知道这是什么原因啊,怎么解决啊!
后面添加的测试用例:

include <QCoreApplication>

include <QSettings>

include <QTextCodec>

include <QStringList>

include <stdio.h>

using namespace std;
int main(int argc, char *argv[])
{

QCoreApplication a(argc, argv);
QString path;
int s = -1;
while(s != 0)
{
    scanf("%d",&s);
    if(s == 1)
    {
       path = "E:\\MyWork\\Test\\TestINI\\debug\\ascii.ini";
    }
    else if(s == 2)
    {
       path = "E:\\MyWork\\Test\\TestINI\\debug\\utf-8_kg.ini";
    }
    else if(s == 3)
    {
       path = "E:\\MyWork\\Test\\TestINI\\debug\\utf-8_nokg.ini";
    }
    else if(s == 4)
    {
       path = "E:\\MyWork\\Test\\TestINI\\debug\\utf-8_hh.ini";
    }
    QSettings set(path, QSettings::IniFormat);
    //set.setIniCodec(QTextCodec::codecForName("UTF-8"));
    //set.setIniCodec(QTextCodec::codecForName("GBK"));
    set.setIniCodec(QTextCodec::codecForName("GBK"));
    set.beginGroup("Event");
    QStringList keys = set.allKeys();
    QMap<QString,QString> theMap;
    theMap.clear();
    printf("s = %d ,%s:\n",s,path.toAscii().data());
    for(int i = 0;i < keys.size();i++)
    {![图片描述][1]
        QString key = keys.at(i);
        QRegExp rx("[A-Fa-f0-9]+");
        if((key.isEmpty())||(!rx.exactMatch(key))||(key.size()!= 4))
        {
            continue;
        }
        QString _nValue = QString(set.value(key).toString().toLatin1());
        printf("%s,   %s  \n",key.toAscii().data(),_nValue.toAscii().data());
        theMap.insert(key,_nValue);
    }
    set.endGroup();
}
return a.exec();

}

怪我咯怪我咯2764 days ago1040

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 13:10:47

    Suggestion
    QString _nValue = QString(set.value(key).toString().toLatin1());

    When the ini encoding is UTF8, change it to
    QString _nValue = QString::fromUtf8(set.value(key).toByteArray());

    When the ini encoding is ASCII, change it to
    QString _nValue = QString::fromLatin1(set.value(key).toByteArray());

    You try it

    reply
    0
  • Cancelreply