Jichao
Jichao

Reputation: 41835

How to save state of a dialog in Qt?

Suppose there are checkboxes, options etc controls in a dialog box, how could I save the state of the dialog in Qt?

Should I use QSettings or something else?

Thanks.

Upvotes: 7

Views: 3044

Answers (2)

Klaas van Aarsen
Klaas van Aarsen

Reputation: 474

I ran into the same problem. Googling didn't help too much. So in the end I wrote my own solution.

I've created a set of functions that read and write the state of each child control of a dialog at creation respectively destruction. It is generic and can be used for any dialog.

It works like this:

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    QMoMSettings::readSettings(this);
}

Dialog::~Dialog()
{
    QMoMSettings::writeSettings(this);
    delete ui;
}

...

void QMoMSettings::readSettings(QWidget* window)
{
    QSettings settings;

    settings.beginGroup(window->objectName());
    QVariant value = settings.value("pos");
    if (!value.isNull())
    {
        window->move(settings.value("pos").toPoint());
        window->resize(settings.value("size").toSize());
        recurseRead(settings, window);
    }
    settings.endGroup();
}

void QMoMSettings::writeSettings(QWidget* window)
{
    QSettings settings;

    settings.beginGroup(window->objectName());
    settings.setValue("pos", window->pos());
    settings.setValue("size", window->size());
    recurseWrite(settings, window);
    settings.endGroup();
}

void QMoMSettings::recurseRead(QSettings& settings, QObject* object)
{
    QCheckBox* checkbox = dynamic_cast<QCheckBox*>(object);
    if (0 != checkbox)
    {
        checkbox->setChecked(settings.value(checkbox->objectName()).toBool());
    }
    QComboBox* combobox = dynamic_cast<QComboBox*>(object);
    if (0 != combobox)
    {
        combobox->setCurrentIndex(settings.value(combobox->objectName()).toInt());
    }
    ...

    foreach(QObject* child, object->children())
    {
        recurseRead(settings, child);
    }
}

void QMoMSettings::recurseWrite(QSettings& settings, QObject* object)
{
    QCheckBox* checkbox = dynamic_cast<QCheckBox*>(object);
    if (0 != checkbox)
    {
        settings.setValue(checkbox->objectName(), checkbox->isChecked());
    }
    QComboBox* combobox = dynamic_cast<QComboBox*>(object);
    if (0 != combobox)
    {
        settings.setValue(combobox->objectName(), combobox->currentIndex());
    }
    ...

    foreach(QObject* child, object->children())
    {
        recurseWrite(settings, child);
    }
}

Hope this helps someone after me.

Upvotes: 11

Nicholas Smith
Nicholas Smith

Reputation: 11754

QSettings will work fine for what you need, but you're essentially just serializing the options and reloading them at start up so there's plenty of documentation on doing it in Qt.

Upvotes: 2

Related Questions