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);
}
阅读价值观
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();
}
第一次正确写入值。但是,如果我再次运行程序,则值会覆盖旧值。有人可以在这里建议我一个解决方案吗? 谢谢
答案 0 :(得分:1)
每次单击“分配”按钮,都会创建新的映射,将用户,密码和角色存储在那里,并将该列表保存到配置文件中。
缺少的是您在修改现有映射之前已阅读它们。 而不是
QVariantMap userPasswordMapping;
QVariantMap userRoleMapping;
做的:
QVariantMap userPasswordMapping = settings.value("Password").value<QVariantMap>();
QVariantMap userRoleMapping = settings.value("Role").value<QVariantMap>();
关于您发布的有关阅读值的代码的其他提示:
QVariant variantRole = settings.value("Password");
这应该是
.value("Role");