實際的運用過程中,常需要應用程序能保存程序的狀態以及用戶的設置,如應用程序顯示的大小,位置,背景顏色或用戶設置的參數等信息,以便在下次運行程序時,能保持上次關閉的狀態。
在Qt的使用過程中,我們使用Qsetting來保存程序的狀態。使得當用戶再次打開時,窗體仍然可以呈現半閉時的狀態。
下面我舉一個簡單的例子加以說明:
貼上代碼:
setting.h:
- #ifndef SETTINGS_H
- #define SETTINGS_H
-
- #include <QDialog>
-
- class QPushButton;
- class QLabel;
- class QTextEdit;
-
- class Settings : public QDialog
- {
- Q_OBJECT
- public:
- Settings();
-
- QLabel *label;
- QPushButton *colorBtn;
- QTextEdit *edit;
-
- void readSettings();
- void writeSettings();
-
- protected:
- void closeEvent(QCloseEvent *);
-
- public slots:
- void slotColor();
- };
-
- #endif // SETTINGS_H
setting.cpp:
- #include "settings.h"
- #include <QtGui>
-
- Settings::Settings()
- {
- setWindowTitle("Settings");
-
- label = new QLabel;
- label->setText("Setting Test");
-
- colorBtn = new QPushButton;
- colorBtn->setText("Select Color");
-
- edit = new QTextEdit;
-
- QGridLayout *layout = new QGridLayout(this);
- layout->addWidget(label,0,0);
- layout->addWidget(colorBtn,0,1);
- layout->addWidget(edit,1,0,1,2);
-
- readSettings();
-
- connect(colorBtn, SIGNAL(clicked()), this, SLOT(slotColor()));
- }
-
- void
- Settings::slotColor()
- {
- QColor color = QColorDialog::getColor (Qt::blue);
-
- if(color.isValid())
- {
- QPalette p = label->palette();
- p.setColor(QPalette::Normal,QPalette::WindowText,color);
- label->setPalette(p);
- }
- }
-
- void
- Settings::readSettings()
- {
- QSettings setting("MyPro","settings");
- setting.beginGroup("Dialog");
- QPoint pos = setting.value("position").toPoint();
- QSize size = setting.value("size").toSize();
- setting.endGroup();
-
- setting.beginGroup("Content");
- QColor color = setting.value("color").value<QColor>();
- QString text = setting.value("text").toString();
- setting.endGroup();
-
- move(pos);
- resize(size);
- QPalette p = label->palette();
- p.setColor(QPalette::Normal,QPalette::WindowText,color);
- label->setPalette(p);
- edit->setPlainText(text);
- }
-
- void
- Settings::writeSettings()
- {
- QSettings setting("MyPro","settings");
- setting.beginGroup("Dialog");
- setting.setValue("position",pos());
- setting.setValue("size",size());
- setting.endGroup();
-
- setting.beginGroup("Content");
- setting.setValue("color",label->palette().color(QPalette::WindowText));
- setting.setValue("text",edit->toPlainText());
- setting.endGroup();
- }
-
- void
- Settings::closeEvent(QCloseEvent *e)
- {
- writeSettings();
- }