Saving the state of a Qt application to a file

2019-07-27 02:55发布

问题:

I am somewhat of a newbie and I can't get the saving and loading to work. The program has some radio buttons and spinboxes, I want to be able to save those positions and values to a file, and be able to open it again later. Here is the saving:

void MainWindow::on_saveButton_clicked()
{
 QString fileName = QFileDialog::getSaveFileName(this,
     tr("Salvesta Projekt"), "",
     tr("Latid Pindalaks (*.lp);;All Files (*)"));

 if (fileName.isEmpty())
     return;
 else {
     QFile file(fileName);
     if (!file.open(QIODevice::WriteOnly)) {
         QMessageBox::information(this, tr("Unable to open file"),
             file.errorString());
         return;
     }
     QDataStream out(&file);
     out.setVersion(QDataStream::Qt_4_8);

     QByteArray MyArray = MainWindow::saveState();

     out << (MyArray);
      }
 }

And here is the Loading

void MainWindow::on_loadButton_clicked()
{
 QString fileName = QFileDialog::getOpenFileName(this,
     tr("Ava Projekt"), "",
     tr("Latid Pindalaks (*.lp);;All Files (*)"));

 if (fileName.isEmpty())
     return;
 else {

     QFile file(fileName);

     if (!file.open(QIODevice::ReadOnly)) {
         QMessageBox::information(this, tr("Pole võimalik faili laadida"),
             file.errorString());
         return;
     }

     QDataStream in(&file);
     in.setVersion(QDataStream::Qt_4_8);

     in >> (MyArray);

     MainWindow::restoreState(MyArray);
 }
}

I know i'm doing something very wrong, so a good example would be very appreciated.

回答1:

QMainWindow documentation states that:

Saves the current state of this mainwindow's toolbars and dockwidgets.

This means that you must save and the state of the other widgets (radio buttons and whatnot) yourself.



回答2:

QSettings is often used to store the state of a GUI application. The following example illustrates how to use QSettings to save and restore the geometry of an application's main window.

 void MainWindow::writeSettings()
 {
     QSettings settings("Moose Soft", "Clipper");

     settings.beginGroup("MainWindow");
     settings.setValue("size", size());
     settings.setValue("pos", pos());
     settings.endGroup();
 }

 void MainWindow::readSettings()
 {
     QSettings settings("Moose Soft", "Clipper");

     settings.beginGroup("MainWindow");
     resize(settings.value("size", QSize(400, 400)).toSize());
     move(settings.value("pos", QPoint(200, 200)).toPoint());
     settings.endGroup();
 }