保存应用程序设置(QSettings)
1. QSettings 类
2. 使用 QSettings
(1)构造一个 QSettings 对象
(2)添加一个设置到 settings 中
/* wrapMargin 是一个子 key
/* 如果存在相同的 key,那么已存在的 key 所对应的值将由新值代替
(3)从 setttings 中取出设置
3. QSettings 的组织方式
(1)用“/”表示子 key
(2)使用 beginGroup( ) 和 endGroup( )
settings.beginGroup("mainwindow") ;
settings.setValue("size", win->size( ) ) ;
settings.setValue("fullScreen", win->isFullScreen( ) ) ;
settings.endGroup( ) ;
settings.beginGroup("outputpanel") ;
settings.setValue("visible", panel->isVisible( ) ) ;
settings.endGroup( ) ;
mainwindow/ size
mainwindow/ fullScreen
outputpanel/ visible
(3)取得 key 与子 key
QSettings settings ;
settings.setValue("fridge/color", Qt::white) ;
settings.setValue("fridge/size", QSize(32, 96) ) ;
settings.setValue("sofa", true) ;
settings.setValue("tv", false) ;
QStringList keys = settings.childKeys( ) ;
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() ;
4. 保存和取得程序的设置
(1)在主窗口的构造函数中,readSettings( )
void MainWindow::readSettings()
{
QSettings settings("Software Inc.", "Spreadsheet"); // 写入与读取的 settings 要一致
restoreGeometry(settings.value("geometry").toByteArray());
recentFiles = settings.value("recentFiles").toStringList();
updateRecentFileActions();
bool showGrid = settings.value("showGrid", true).toBool();
showGridAction->setChecked(showGrid);
bool autoRecalc = settings.value("autoRecalc", true).toBool();
autoRecalcAction->setChecked(autoRecalc);
}
(2)在关闭主窗口时,writeSettings( )
void MainWindow::writeSettings()
{
QSettings settings("Software Inc.", "Spreadsheet");
settings.setValue("geometry", saveGeometry());
settings.setValue("recentFiles", recentFiles);
settings.setValue("showGrid", showGridAction->isChecked());
settings.setValue("autoRecalc", autoRecalcAction->isChecked());
}
/* 这