Как объяснено в других ответах, в C ++ просто нет механизма, который мог бы в общих чертах иметь дело с сериализацией и десериализацией состояний / переменных вашей программы.Все методы будут включать рукописный код, чтобы явно иметь дело с такой функциональностью.
В частности, о QSettings, вы можете, например, добавить 2 метода в ваш QMainWindow (при условии, что вы используете один, если нет, то какой бы класс ни был тем, которыйимеет доступ к необходимым состояниям вашей программы), которые сохраняют и восстанавливают состояния с помощью объекта QSettings.
Что-то вроде:
void MainWindow::saveStateToSettings() // QMainWindow already has method saveState() to store dockwidgets and toolbars locations and visibility, so don't use that function name for this
{
QSettings settings; // the QSettings default constructor can be made to have default parameters like shown in the main() function code below
settings.setValue("mywindowgeometry",saveGeometry()); // QWidget::saveGeometry is the recommended way to serialize the position, size and monitor number etc of QWidget
settings.setValue("myvariable1",m_myVariable1); // m_myVariable1 could be any of various basic C++ or Qt value datatypes, like int, float, QString, QRect, QByteArray etc, let's assume here it is a double floating point number. DON'T store pointers using this, serializing pointers is almost always useless and/or dangerous
settings.setValue("checkbox1checked",ui->checkBox->isChecked()); // store a bool
settings.setValue("plaintextedit1text",ui->plainTextEdit->toPlainText()); // store a QString
// write similar code as above to save all other needed state
// that's all there is to it to save the state!
}
void MainWindow::loadStateFromSettings()
{
QSettings settings;
restoreGeometry(settings.value("mywindowgeometry").toByteArray()); // QWidget::restoreGeometry restores the widget geometry from data that was generated previously with QWidget::saveGeometry
m_myVariable1=settings.value("myvariable1",0.5).toDouble(); // the 0.5 sets a default value if the QSettings instance is missing the variable or there's some other problem with the QSettings instance
ui->checkBox->setChecked(settings.value("checkbox1checked",true).toBool()); // again, the "true" value will be used in case of problem with QSettings
ui->plainTextEdit->setPlainText(settings.value("plaintextedit1text").toString()); // no value as the default value "magically" gives an empty QString
}
Обратите внимание, что для правильной работы restoreGeometry, loadStateFromSettings() вызов должен быть сделан после создания виджета, не вызывайте его в самом конструкторе класса виджета.Ваша функция main () может выглядеть примерно так:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSettings::setDefaultFormat(QSettings::IniFormat); // now QSettings default constructor anywhere in the program code creates a QSettings object that uses ini-files. Note that on Windows you could use the registry and on Mac plist-files. Read the QSettings documentation for more on this
QApplication::setApplicationName("MyApplication"); // you should set this for your app object so QSettings can store the settings for your app in a location that can be identified by that name
QApplication::setOrganizationName("MyName"); // you should set this for your app object, the organization name is effectively your "company" name, and it makes QSettings store the settings for your app(s) in a location that can be identified by that name
MainWindow w;
w.loadStateFromSettings();
w.show();
return a.exec();
}
Я набрал это в основном из памяти, поэтому код не гарантированно компилируется и работает напрямую, но, надеюсь, это даст вам представление о том, как это сделать.об этом.