Qt checkbox stateChanged event handler

21,653

Connect QCheckBox::clicked(bool checked) signal to your slot:

QCheckBox *cb = new QCheckBox(this);
connect(cb, SIGNAL(clicked(bool)), this, SLOT(toggled(bool)));

This signal is not emitted if you call setDown(), setChecked() or toggle().

Share:
21,653
Stan
Author by

Stan

Updated on July 13, 2020

Comments

  • Stan
    Stan almost 4 years

    In my Qt application, I want to use a checkbox to do A when it's toggled to unchecked, and do B when toggle to checked. The checkbox is hooked to foo(int).

    connect(myCB, SIGNAL(stateChanged(int)), this, SLOT(foo(int)));
    

    There's a problem when the sanity check fails (eg. some variable got invalid values), I want to just show error message and remain everything unchanged. So I toggle the checkbox again to revert it back to where it was. But it seems this action would trigger the callback function foo(int) again, which mess up everything. I don't want it to trigger the callback in this situation. How should I do? Or is there a better way? See the pseudo code below.

    void foo(int checkState)
    {
      if (checkState == Qt::Unchecked) {
        if (!passSanityCheck()) {
          // show error message
          checkBoxHandle->toggle();
          return;
        }
    
        // do A when it's unchecked
      }
      else {
        if (!passSanityCheck()) {
          // show error message
          checkBoxHandle->toggle();
          return;
        }
    
        // do B when it's checked
      }
      return;
    }