سؤال

I am creating a config file which stores username, password and role of certain user. I am using the following code.

void MainWindow::OnAssignButtonClicked()
{
   QSettings settings("/root/configFile.ini", QSettings::IniFormat);

   QString userName = lineEditUsername.text();
   QString password = lineEditPassword.text();
   QString Role = comboBox.currentText();

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

  QVariantMap userPasswordMapping;
  QVariantMap userRoleMapping;

  listUsername << userName;
  listPassWord << Password;
  listRole << Role;

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

   userPasswordMapping[user] = pass;
   userRoleMapping[user] = role;
  }

 // Store the mapping.
  settings.setValue("Password", userPasswordMapping);
  settings.setValue("Role",userRoleMapping);

}

While Reading the Values

 QVariant variantPassword = settings.value("Password");
 QVariant variantRole = settings.value("Password");
 QVariantMap mapPassword = variantPassword.value<QVariantMap>();
 QVariantMap mapRole = variantRole.value<QVariantMap>();
 QMapIterator<QString, QVariant> iteratorPassword(mapPassword);
 QMapIterator<QString, QVariant>iteratorRole(mapRole);
  while (iteratorPassword.hasNext()) 
  {
      iteratorPassword.next();
      QString user = iteratorPassword.key();
      QString pass = iteratorPassword.value().toString();
      iteratorRole.next();
      QString role = iteratorRole.value().toString();   
   }

The first time the value gets written correctly. However if I run the program again the value over writes the old values. Can some one please suggest me a solution here? Thank You

هل كانت مفيدة؟

المحلول

Every time you click your 'assign' button, you create new mappings, store the user, password and role in there and save that list to the config file.

What is missing is that you read the existing mappings before modifying them. Instead of

QVariantMap userPasswordMapping;
QVariantMap userRoleMapping;

do:

QVariantMap userPasswordMapping = settings.value("Password").value<QVariantMap>();
QVariantMap userRoleMapping = settings.value("Role").value<QVariantMap>();

Additional hint about the code you posted about reading the values:

QVariant variantRole = settings.value("Password");

this should be

.value("Role");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top