[SOLVED]About restoring the Mainwindow not for the first time
-
The problem is that how to set a defult size and state only for the first time? After the first time, the state and size are used the settings for the last time.
I have implemented the function to store the current size and splitter state. And in the constructor, call the RestoreState function instead of setting as default state and size.
However, at the first time when running the program, the size is too small, just because of without stored size and state at the first time. How to solve this problem?
The following is the code I have implemented,
@// store state when close
void MainWindow::closeEvent(QCloseEvent *event)
{
QSettings settings("xxx", "xxxxx");
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.setValue("splitterState", ui->splitter->saveState());
settings.endGroup();
}@@// restore the state and size in the constructor
void MainWindow::readSettings()
{
QSettings settings("xxx", "xxxxx");
settings.beginGroup("MainWindow");
resize(settings.value("size").toSize());
move(settings.value("pos").toPoint());
ui->splitter->restoreState(settings.value("splitterState").toByteArray());
settings.endGroup();
}@I think, the key point is that how to let the program know whether it is the first running or not.
Thanks!
-
See if the size returned is a valid QSize. If not, assume it's the first time.
@
void MainWindow::readSettings()
{
QSettings settings("xxx", "xxxxx");
settings.beginGroup("MainWindow");QSize size = settings.value("size").toSize(); if (size.isValid()) { resize(size); move(settings.value("pos").toPoint()); ui->splitter->restoreState(settings.value("splitterState").toByteArray()); } else { // handle first time usage. } settings.endGroup();
}
@ -
Well, either store some "FirstRun" flag in your QSettings object, just like you store the other options.
...or set a reasonable default value for the "size" option.
@QSize defaultSize(800, 600); //Adjust default as needed!
resize(settings.value("size", defaultSize).toSize()); //Pass a default to QSettings::value()@ -
[quote author="MuldeR" date="1335282358"]Well, either store some "FirstRun" flag in your QSettings object, just like you store the other options.
...or set a reasonable default value for the "size" option.
@QSize defaultSize(800, 600); //Adjust default as needed!
resize(settings.value("size", defaultSize).toSize()); //Pass a default to QSettings::value()@[/quote]That's a fine approach too. For the record, I had used the valid test in order to be able to create a block of code that he could use to do any other "first-time" initialization. They're all valid solutions, though.