How to change the state of the checkbox



  • I want to perform an operation based on the push button press.

    i.e : I have 5 Checkboxes . When i press the push button i want to check all the check box and when i press the same button i want to uncheck all the check boxes is there any simlplest way ?

    My Code:

    if(ui->pushButton->text() == "Select All")
    {
    ui->checkBox->setChecked(true);
    ui->checkBox_2->setChecked(true);
    ui->checkBox_3->setChecked(true);
    ui->checkBox_4->setChecked(true);
    ui->checkBox_5->setChecked(true);

        ui->pushButton->setText("Unselect All");
    }
    else
    {
        ui->checkBox->setChecked(false);
        ui->checkBox_2->setChecked(false);
        ui->checkBox_3->setChecked(false);
        ui->checkBox_4->setChecked(false);
        ui->checkBox_5->setChecked(false);
        ui->pushButton->setText("Select All");
    }
    

    Is there any different and easy way than this?



  • @ManiRon
    Well, in some shape or form that is indeed what you need to do. Do you mean you'd like hints to write it in less than your 20-odd lines?



  • const bool checked = (ui->pushButton->text() == QLatin1String("Select All"));
    for(auto checkBox : {ui->checkBox,ui->checkBox_2,ui->checkBox_3,ui->checkBox_4,ui->checkBox_5})
        checkBox->setChecked(checked);
    ui->pushButton->setText(checked ? QStringLiteral("Unselect All"):QStringLiteral("Select All"));
    


  • @VRonin
    That's the sort of thing I had in mind. I'm sure we could squeeze a few more characters out of it if we tried :)

    One minor question, to avoid the OP being confused: is there a reason you have gone for QLatin1String when comparing the button text but QStringLiteral when setting it?



  • @JonB said in How to change the state of the checkbox:

    is there a reason you have gone for QLatin1String when comparing the button text but QStringLiteral when setting it?

    from https://woboq.com/blog/qstringliteral.html

    • Most of the cases: QStringLiteral("foo") if it will actually be converted to QString
    • QLatin1String("foo") if it is use with a function that has an overload for QLatin1String
    • QString::operatopr== has a QLatin1String overload so I use QLatin1String.
    • QPushButton::setText does not have such overload so I use QStringLiteral


  • @VRonin
    Ah ha! So (IMHO) as efficient as possible and as clear as mud ;-) I love C++....


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.