Search code examples
c++qtqt4qcheckbox

Save the state of QCheckBox in file, and load the state when program restarts


In my GUI application, I have some labels in my mainwindow the visibility of the labels are controlled from checkboxes in a dialog which opens when a button (setting) is pressed. Now, it all works fine, i.e. if I open the settings dialog I can check or uncheck the checkboxes; consequently the labels are also set visible or invisible.

mysettingsdialog.cpp

void mysettingsdialog::onclick(bool checked)      //by AJ kpi conf
{
    if(myCheckBox->isChecked()==true)
    {
        emit setlabelvisible();
    }
    else
    {
        emit setlabelinvisible();
    }
}

mainwindow.cpp

MySettingsDialog* myset=new MySettingsDialog(this);
connect(myset,SIGNAL(setlabelvisible()),this,SLOT(enable1()));          
connect(myset,SIGNAL(setlabelinvisible()),this,SLOT(disable1()));

void MainWindow::enable1()      
{
    ui->label->setVisible(true);
    qDebug()<<"VISIBLE label";
}
void MainWindow::disable1()     
{
    ui->label->setVisible(false);
    qDebug()<<"INVISIBLE label";
}

Now the problem is, every time my application restarts it does not retain the previous state of the checkboxes. So I was thinking to save the state of the checkbox in a variable and writing it to a file, so whenever my application starts it will read the file and set the status of check box accordingly.

My question is, how can I store the "state" of checkbox in a variable and write it to file. And again use the same to set the state of checkbox ???

I mean reading / writing values from file for QLabels and QLineEdits is easy enough but I am baffled about how to do it with checkbox.


Solution

    1. Create a container to store the pointer of each checkbox.
    2. Create another container to store the "state" of each checkbox. For a binary check box, you can use isChecked() to query whether or not a checkbox is checked. Otherwise you can call checkState() to return the state as enum if you use a tri-state check box (see the edit).
    3. When loading settings, assign the state to each check box accordingly.

    4. You may use QSettings to manage the settings and save them as an ini file.


    Edit

    Just mention there is an option for a tri-state check box. From the document:

    QCheckBox optionally provides a third state to indicate "no change". This is useful whenever you need to give the user the option of neither checking nor unchecking a checkbox. If you need this third state, enable it with setTristate(), and use checkState() to query the current toggle state.