How can I verify if the checkbox is checked or not in Qt?

29,485

Solution 1

Unless you are using a tristate checkbox, you can simply if (checkbox->isChecked())

This property is inherited way back in QAbstractButton. If it is a tristate checkbox, you will have to use checkState() as suggested in the other answer.

Solution 2

I think checkState doesn't take any argument. Try if(checkbox->checkState() == Qt::Unchecked)

Solution 3

maybe you can try like this?

QCheckBox *checkbox = new QCheckBox("paid with cash!", this);
checkbox->setChecked(false);

then for if command..

if(!checkbox->isChecked)
{
     nameLine->setText("the box is unchecked");
}
Share:
29,485
user3396248
Author by

user3396248

Updated on December 01, 2020

Comments

  • user3396248
    user3396248 over 3 years

    The following code is supposed to set the text of nameLine form to this box is unchecked when the QCheckBox instance checkbox has state Unchecked.

    Here is the my checkbox instance declaration:

    QCheckBox *checkbox = new QCheckBox("paid with cash!", this);
    checkbox->setCheckState(Qt::Unchecked);
    

    and here is the logic so far:

    if(checkbox->checkState(Qt::Unchecked))
    {
        nameLine->setText("the box is unchecked");
    }
    

    This code does not compile. The resulting error is the following:

    C:\Qt\5.1.1\mingw48_32\examples\widgets\tutorials\addressbook\part1\voruskra.cpp:144: error: no matching function for call to 'QCheckBox::checkState(Qt::CheckState)'
        if(checkbox->checkState(Qt::Unchecked))
                                             ^
    

    Can you tell me what I am doing wrong?

    • dtech
      dtech over 9 years
      So basically, this is a program that lies about the checkbox?
  • user3396248
    user3396248 over 9 years
    yea i figured right after my comment, but then it always goes in the in the if statement, both if the checkbox is checked or not :(
  • chwi
    chwi over 9 years
    Then some other thing is wrong, because this is the correct answer.
  • rbaleksandar
    rbaleksandar over 2 years
    Often isChecked() is enough however this here is the full answer since a checkbox actually has 3 states - unchecked, partially checked and checked. A good example for partially checked is often seen in tree views where only a portion of nodes in a subtree are checked leading to a partially checked state for the subtree itself.