Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save state of a dialog in Qt?

Tags:

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.

like image 243
Jichao Avatar asked Jun 25 '12 07:06

Jichao


2 Answers

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.

like image 132
Klaas van Aarsen Avatar answered Nov 10 '22 16:11

Klaas van Aarsen


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.

like image 2
Nicholas Smith Avatar answered Nov 10 '22 16:11

Nicholas Smith