Search code examples
qt

How to make Toggle Functionality with QT?


I want to make one toggle functionality in QT like when I click on the pushButton then I want something else in the Label and when I click another time then I want another text value.

void MainWindow::on_pushButton_clicked(bool checked)
{
    if (checked) {
        ui->label->setText("Yupp It's working..!!");
    }
    else {
        ui->label->setText("Toggle completed..!!");
    }

}

So what I want is that when I click for the first time I want Yupp It's working..!! and second time Toggle completed..!! and third time repeat this.

I try 2 slots

  1. clicked()
  2. toggled()

But it is not working for both slots. It looks like not go inside the function.


Solution

  • To achieve toggle functionality in Qt using a QPushButton, you need to make sure your button is set to be checkable (setCheckable(true)), as you mentioned. Here’s how you can modify your code to toggle between two different texts each time the button is clicked:

    Ensure your QPushButton is set to be checkable in the constructor of your MainWindow class:

    ui->pushButton->setCheckable(true);