本文先从概念和用法上讲述下QSettings的简单用法,最后以一个简单而较全面的使用例子结束,一句话:实践出真知!
QSettings 类提供“持久性”,平台独立的应用程序设置。意思是,程序关闭后QSettings把窗体大小,位置,用户设置的Option 保存起来,下次
打开程序时再重新加载。
如果你需要的是“非持久性” 基于内存的数据结构,可以考虑使用QMap<QString,QVariant> 代替。
通常,对于Windows,配置信息保存在“注册表”中,Mac OS 是XML 文件,Unix 是INI 文件
// 构造函数
QSettings settings("MySoft", "Star Runner"); // 公司或组织名 // 应用程序名
QCoreApplication::setOrganizationName("MySoft");
QCoreApplication::setOrganizationDomain("mysoft.com"); // 专为Mac OS X 准备的
QCoreApplication::setApplicationName("Star Runner");
...
QSettings settings;
如果要在程序很多地方使用QSettings,用 QCoreApplication::setOrganizationName() 和QCoreApplication::setApplicationName() 然后用QSettings 的默认构造函数。
这样,公司或组织名,应用程序名只要指定一次,QSettings settings 到处扔就行。
QSettings 存储了一对键值( Key / value ) ,Key 是一个QString,Value是一个QVariant
settings.setValue("editor/wrapMargin", 68); //添加一对键值
添加键值的时侯,如果Key 已存在,则Value 被重写。
出于效率的原因,setValue 不会立既写入(如注册表,INI, XML), 要立既写入可以用sync() 函数。
int margin = settings.value("editor/wrapMargin").toInt();
通过Key,取回Value。如果指定的Key 不存在,QSettings 返回空的QVariant(转成整型是 0)。
// 类型转换
QSettings settings("MySoft", "Star Runner");
QColor color =settings.value("DataPump/bgcolor").value<QColor>();
// 通过"/" 分组
settings.setValue("mainwindow/size",win->size());
settings.setValue("mainwindow/fullScreen",win->isFullScreen());
settings.setValue("outputpanel/visible",panel->isVisible());
settings.beginGroup("mainwindow");
settings.setValue("size", win->size());
settings.setValue("fullScreen",win->isFullScreen());
settings.endGroup();
settings.beginGroup("outputpanel");
settings.endGroup();
添加分组,并链表化,读写分组
void QSettings :: beginWriteArray ( const QString & prefix , int size = - 1 )
Adds prefix to the current group and starts writing an array of size size.
If size is -1 (the default), it is automatically determined based on the indexes of the entries written.
If you have many occurrences of a certain set of keys,
you can use arrays to make your life easier.
For example, let's suppose that you want to save a variable-length list of user names and passwords.
You could then write:
struct Login{
QString userName;
QString password;
};
QList<Login> logins;
...
QSettings settings;
settings.beginWriteArray("logins");
for (int i = 0; i < logins.size(); ++i) {
settings.setArrayIndex(i);
settings.setValue("userName", list.at(i).userName);
settings.setValue("password", list.at(i).password);
}
settings.endArray();
遍历分组
int QSettings::beginReadArray(constQString&prefix)
Adds prefix to the current group and starts reading from an array. Returns the size of the array.
Example:
struct Login {
QString userName;
QString password;
};
QList<Login> logins;
...
QSettings settings;
int size = settings.beginReadArray("logins");
for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
Login login;
login.userName = settings.value("userName").toString();
login.password = settings.value("password").toString();
logins.append(login);
}
settings.endArray();
Returns a list of all key top-level groups that contain keys that can be read using the QSettings object.
Example:
QSettings settings;
settings.setValue("fridge/color", Qt::white);
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", true);
settings.setValue("tv", false);
QStringList groups = settings.childGroups();
// groups: ["fridge"]
If a groupisset usingbeginGroup(),thefirst-levelkeysin that group are returned,withoutthegroup prefix.
settings.beginGroup("fridge");
groups = settings.childGroups();
// groups: []
You can navigate through the entire setting hierarchy using childKeys() and childGroups() recursively.
See also childKeys() and allKeys().
// readSettings() /writeSettings()
void MainWindow::writeSettings()
{
QSettings settings("Moose Soft", "Clipper");
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
void MainWindow::readSettings()
{
QSettings settings("Moose Soft", "Clipper");
settings.beginGroup("MainWindow");
resize(settings.value("size", QSize(400, 400)).toSize());
move(settings.value("pos", QPoint(200, 200)).toPoint());
settings.endGroup();
}
// readSettings() and writeSettings() 必须分别位于主窗体的构造函数和closeEvent函数里面。
MainWindow::MainWindow()
{
...
readSettings();
}
void MainWindow::closeEvent(QCloseEvent*event)
{
if (userReallyWantsToQuit()) {
writeSettings();
event->accept();
} else {
event->ignore();
}
}
简单用例
main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QList>
#include<QSettings>
#include<QFile>
#include<QStringList>
#include<QDebug>
struct Login {
QString userName;
QString password;
};
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QList<Login> logins;
Login lg1[5];
for(int i=0;i<5;i++){
lg1[i].userName=QString("log%1").arg(i);
lg1[i].password="000";
logins<<lg1[i];
}
QString myfile="test.ini";
QSettings *settings=new QSettings(myfile,QSettings::IniFormat);
settings->beginWriteArray("logins1");//写数组logins1
for (int i = 0; i < logins.size(); ++i) {
settings->setArrayIndex(i);
settings->setValue("userName", logins.at(i).userName);
settings->setValue("password", logins.at(i).password);
}
QList<Login> logins2;
Login lg2[5];
for(int i=0;i<5;i++){
lg2[i].userName=QString("log%1").arg(i+5);
lg2[i].password="000";
logins2<<lg2[i];
}settings->endArray();
//QString myfile="test.txt";
//QSettings *settings=new QSettings(myfile,QSettings::IniFormat);
settings->beginWriteArray("logins2");//写数组logins2
for (int i = 5; i < logins2.size()+5; ++i) {
settings->setArrayIndex(i);
settings->setValue("userName", logins2.at(i-5).userName);
settings->setValue("password", logins2.at(i-5).password);
}
settings->endArray();
QStringList groups = settings->childGroups();
foreach(QString str,groups)//列出所有子组
qDebug()<<str;
//QSettings
int size = settings->beginReadArray("logins1");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
Login login;
login.userName = settings->value("userName").toString();
login.password = settings->value("password").toString();
logins.append(login);
}
settings->endArray();
qDebug()<<logins.size();
for(int i=0;i<logins.size();i++)
{
qDebug()<<i<<logins[i].userName;
}
size = settings->beginReadArray("logins2");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
Login login;
login.userName = settings->value("userName").toString();
login.password = settings->value("password").toString();
logins.append(login);
}
settings->endArray();
qDebug()<<logins.size();
for(int i=0;i<logins.size();i++)
{
qDebug()<<i<<logins[i].userName;
}
settings->beginWriteArray("maingroup");
//for (int i = 5; i < logins2.size()+5; ++i) {
settings->setValue("userName", "root");
settings->setValue("password", "000");
//}
settings->endArray();
qDebug()<<settings->value("maingroup/userName").toString();//列出maingroup下userName的值
}
MainWindow::~MainWindow()
{
delete ui;
}