以前项目中读写ini配置文件,都是以单个key-value形式进行读写,现在项目中又用到了需要把数据数组放置到ini配置文件中,这里结合Qt官方文档进行验证和总结。
配置文件中数据格式,存放三组数据,如图1所示:
图1
1、写入数据
1 void WriteIni() { 2 QList<Login> logins_list; 3 Login log1; 4 log1.userName = "test1"; 5 log1.password = "1111"; 6 logins_list.append(log1); 7 8 Login log2; 9 log2.userName = "test2"; 10 log2.password = "2222"; 11 logins_list.append(log2); 12 Login log3; 13 log3.userName = "test3"; 14 log3.password = "3333"; 15 logins_list.append(log3); 16 17 QSettings settings("config.ini", QSettings::IniFormat); 18 settings.beginWriteArray("BaseInfo"); 19 for (int i = 0; i < logins_list.size(); ++i) { 20 settings.setArrayIndex(i); 21 settings.setValue("password", logins_list.at(i).password); 22 settings.setValue("userName", logins_list.at(i).userName); 23 } 24 settings.endArray(); 25 }
2、读取数据
1 void ReadIni() { 2 QList<Login> logins; 3 4 QSettings settings("config.ini", QSettings::IniFormat); 5 int size = settings.beginReadArray("BaseInfo"); 6 for (int i = 0; i < size; ++i) { 7 settings.setArrayIndex(i); 8 Login login; 9 login.userName = settings.value("userName").toString(); 10 login.password = settings.value("password").toString(); 11 logins.append(login); 12 } 13 settings.endArray(); 14 15 for (int i = 0; i < logins.length(); ++i) { 16 qDebug() << logins[i].userName; 17 qDebug() << logins[i].password; 18 } 19 }