配置文件被qt覆盖

时间:2013-09-20 12:52:17

标签: qt config

我使用以下代码将数据写入配置文件。

   QSettings settings("/root/configFile.ini",QSettings::IniFormat);

   QString userName = lineEditUsername.text();
   QString password = lineEditPassword.text();

   QList<QString> listUsername;
   QList<QString> listPassword;

   settings.beginWriteArray("UserData");

   for(i=0;i<listUsername.size();i++)
  {
      Qstring user = listUsername.at(i);         
      Qstring pass = listPassword.at(i);

      settings.setArryIndex(i);
      settings.setValue("Username",user);
      settings.setValue("Password",pass);
   }

  settings.endArray();
 }

现在,当我第一次运行代码并给出4或5个值时,它们在文件中以正确的顺序形成。但是,如果我第二次运行应用程序,则值将从第一个位置开始覆盖。有人可以建议我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

我建议创建用户凭据映射并将其存储在设置文件中,而不是创建和维护数组和索引,如下所示:

QSettings settings("/root/configFile.ini", QSettings::IniFormat);

QString userName = lineEditUsername.text();
QString password = lineEditPassword.text();

QList<QString> listUsername;
QList<QString> listPassword;

//settings.beginWriteArray("UserData");

QVariantMap userDataMapping;

for(int i = 0; i < listUsername.size() ; i++)
{
    QString user = listUsername.at(i);         
    QString pass = listPassword.at(i);

    userDataMapping[user] = pass;

    //settings.setArryIndex(i);
    //settings.setValue("Username",user);
    //settings.setValue("Password",pass);
}

// Store the mapping.
settings.setValue("UserData", userDataMapping);

//settings.endArray();
// ...

这将以下列格式将您的数据存储在ini文件中:

UserData=@Variant(\0\0\0\b\0\0\0\x1\0\0\0\x6\0\x64\0\x64\0\x64\0\0\0\n\0\0\0\x6\0\x62\0\x62\0\x62)

当您阅读设置时,请执行以下操作:

[..]
QVariant v = settings.value("UserData");
QVariantMap map = v.value<QVariantMap>();
QMapIterator<QString, QVariant> i(map);
while (i.hasNext()) {
    i.next();
    QString user = i.key();
    QString pass = i.value().toString();
}

答案 1 :(得分:0)

您需要在添加新条目之前检索现有条目的数量。像这样:

int size = settings.beginReadArray( "UserData" );
settings.endArray();

settings.beginWriteArray( "UserData" );
settings.setArrayIndex( size );  // Note: Maybe 'size - 1', not  sure

// ...
settings.endArray();

setArrayIndex( size )会将数组索引移动到结尾,因此不再覆盖现有条目