1

I'm working in a Qt project where the user can enable or disable a QPushButton by selecting or deselecting a QCheckBox.
I have already developed a function where the mouse event enable the QPushButton, but the problem is that when i deselect the QCheckBox the QPushButton remain enabled.
Is there a Qt function to disable a button when QCheckBox are unchecked?

This is the code i wrote:

//Class.h
//Function to enable the button
private slots:
   void on_QCheckBox_clicked();
//Class.cpp
void class::on_QCheckBox_clicked() {
  ui->QPushButton->setEnabled(true);
  //Here i enabled the button with setEnabled function
}
demonplus
  • 5,613
  • 12
  • 49
  • 68
  • Can you share your complete code, so we can check that. – Vahagn Avagyan Jul 28 '17 at 13:00
  • This is the relevant part of the code...other isn't about this problem. –  Jul 28 '17 at 13:03
  • There is a signal named QCheckBox::stateChanged(int state), you should use it. Also you should provide the code that connects the signals together – k_kaz Jul 28 '17 at 13:04
  • 1
    Qt5: `QObject::connect(pQTglBtnEn, &QCheckBox::toggled, pQBtn, &PushButton::setEnabled);` with `QCheckBox *pQTglBtn;` and `QPushButton *pQBtn;` – Scheff's Cat Jul 28 '17 at 13:20
  • 2
    Qt4: `QObject::connect(pQTglBtnEn, SIGNAL(toggled(bool)), pQBtn, SLOT(setEnabled(bool)));` with `QCheckBox *pQTglBtn;` and `QPushButton *pQBtn;` – Scheff's Cat Jul 28 '17 at 13:22
  • Thanks @Scheff! Yours solution works! –  Jul 28 '17 at 13:31
  • Yes, I know. ;-) You find a similar sample in my answer for [SO: QPushButton doesn't update when setDown is called](https://stackoverflow.com/a/45267593/7478597). While toying around in my local code I added exactly the feature you asked for (and tested it). – Scheff's Cat Jul 28 '17 at 13:36

2 Answers2

1

Thanks to @Scheff!

I solved by using QObject::connect() to connect my QCheckBox and my QPushButton together

Here is an example:

class::class() {
  QObject::connect(ui->QCheckBox, &QCheckBox::toggled, ui->QPushButton, &QPushButton::setEnabled);
  //Where ui->QCheckBox is the checkbox and ui->QPushButton is your button
}
0

You can check the state using QCheckBox::checkState() as follows:

if (QCheckBox->checkState() == Qt::Unchecked)
{
    ui->QPushButton->setEnabled(false);
}
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88