Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt checkbox stateChanged event handler

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;
}
like image 813
Stan Avatar asked Sep 06 '13 10:09

Stan


1 Answers

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().

like image 144
thuga Avatar answered Nov 01 '22 09:11

thuga