user8467047
user8467047

Reputation:

QT - Detecting which button was pressed

I have a problem with the usage of Application::sender. I have a few QPushButtons and in one function, I want to detect which button was pressed.

I got to know that using Application::sender might be the solution, however I have troubles with it. Namely I get two errors:

And here is my code:

void MainWindow::on_button_click()
{
    unsigned long i=0;
    for(; i<buttons.size(); ++i)
    {
        if(buttons[i] == QApplication::sender())
            break;
    }
    if(checks[i]->checkState() == false)
        buttons[i]->setText("Undone");
    else
        buttons[i]->setText("Done!");
}

Where variable buttons is a vector of QPushButton *

Upvotes: 0

Views: 431

Answers (2)

chm
chm

Reputation: 485

sender() returns QObject. You need QPushButton so your have to use casting. This code will work:

QPushButton *button = qobject_cast<QPushButton*>(sender());
button->setText("New Text");

Upvotes: 0

Sergio Monteleone
Sergio Monteleone

Reputation: 2886

Call the method sender() of the object where your slot is, not the static member of QApplication.

In other words, remove QApplication:: and your code should work as expected.

Upvotes: 1

Related Questions