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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With