下面是一个例程:
包含三个文件:
settings.h
settings.cpp
main.cpp
settings.h:
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QtGui/QDialog>
class QLabel;
class QPushButton;
class QTextEdit;
class Settings : public QDialog
{
Q_OBJECT
public:
Settings(QWidget *parent = 0, Qt::WFlags flags =0);
~Settings();
void readSettings();
void writeSettings();
protected:
void closeEvent(QCloseEvent *);
public slots:
void slotColors();
private:
QLabel *label;
QPushButton *colorbutton;
QTextEdit *edit;
};
#endif SETTINGS_H
settings.cpp:
#include "settings.h"
Settings::Settings(QWidget *parent, Qt::WFlags flags)
: QDialog(parent, flags)
{
this->setWindowTitle(tr("Settings"));
this->label=new QLabel;
this->colorbutton=newQPushButton;
this->colorbutton->setText(tr("SelectColor"));
this->edit=new QTextEdit;
QGridLayout *mainLayout=newQGridLayout(this);//网格布局
mainLayout->addWidget(this->label,0,0);
mainLayout->addWidget(this->colorbutton,0,1);
mainLayout->addWidget(this->edit,1,0,1,2);
readSettings();
this->connect(this->colorbutton,SIGNAL(clicked()),this,SLOT(slotColors()));
}
Settings::~Settings()
{
}
void Settings::closeEvent(QCloseEvent * e)
{
writeSettings();
}
void Settings::readSettings()//读取程序设置
{
QSettings setting("My Pro","settings");
QPointpos=setting.value("position").toPoint();
QSize size=setting.value("size").toSize();
QColorcolor=setting.value("color").value<QColor>();
QStringtext=setting.value("text").toString();
this->move(pos);
this->resize(size);
QPalette p=label->palette();
p.setColor(QPalette::Normal,QPalette::WindowText,color);
label->setPalette(p);
edit->setPlainText(text);
}
void Settings::writeSettings()//保存程序设置
{
QSettings settings("My Pro","settings");
settings.setValue("position",pos());
settings.setValue("size",size());
settings.setValue("color",label->palette().color(QPalette::WindowText));
settings.setValue("text",edit->toPlainText());
}
main.cpp:
#include "settings.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Settings w;
w.show();
return a.exec();
}
---------------------------------补充---------------------------------------
1.如果程序中有多个地方需要到QSettings,可在main函数中使用如下方式来设置好应用程序的公司名和程序名如:
QCoreApplication::setApplicationName("Settings");
QCoreApplication::setOrganizationName("MyPro");
这样每次用到QSettings,可直接创建对象而不一用输入参数如:
QSettings settings;
2.当保存的信息较多的时候可使用组(Group)的方式
如:
setting.beginGroup("Dialog");
QPointpos=setting.value("position").toPoint();
QSize size=setting.value("size").toSize();
setting.endGroup();
setting.beginGroup("content");
QColorcolor=setting.value("color").value<QColor>();
QStringtext=setting.value("text").toString();
setting.endGroup();
若只要保存某组中的一个信息时,可写成如下方式即可:
QPoint pos=setting.value("Dialog/position").toPoint();
3.数据类型的转换
QPoint pos=setting.value("position").toPoint();
等同于
QPointpos=setting.value("position").value<QPoint>();