MHM
MHM

Reputation: 261

How to know which button was clicked in Qt?

I have 8 buttons in my form (btn1, btn2, btn3, ..., btn8). Each button's text is from a database. I define 8 functions in my database. These are my fields:

ID, Text, Active  

When user presses each button, then I should save the function name in the database. At first, all buttons are hidden. In page load, I read data from database to show the text of function button; if the function button is not active then the button is also invisible.

This is my code :

ui->btn1->hide();
ui->btn2->hide();
ui->btn3->hide();
ui->btn4->hide();
ui->btn5->hide();
ui->btn6->hide();
ui->btn7->hide();
ui->btn8->hide();
 QSqlQueryModel *lst=database->getFunctions();
 QString st;

 QStringList btnlst;
 for(int i = 0; i < lst->rowCount(); ++i)
 {
     if(lst->record(i).value(2).toInt()==1)//ACTIVE
     {
         btnlst<<(lst->record(i).value(3).toString());//text
     }
 }
 for(int i = 0; i < btnlst.count(); ++i)
 {
     QPushButton *btn=this->findChild<QPushButton>(st.append(QString::number(i)));
     btn->setText(btnlst[i]);
     btn->show();
     connect(btn,SIGNAL(clicked()),this,SLOT(Function()));
 }  

In that code, I save all active functions in a list and then get the list count. For example, if the length of the list is 3, so the btn1, btn2 and btn3 should show in my form and the others should stay hidden. Then I connect all of the buttons clicked() signal to a slot called Function().

I want to use the text of the button that the user pressed in my form. How to find which button was clicked, and how to get the text of this button?

Upvotes: 8

Views: 12727

Answers (1)

IAmInPLS
IAmInPLS

Reputation: 4125

In your slot Function(), just retrieve the button you have clicked thanks to QObject::sender(), and then you can get the text of that button with QAbstractButton::text():

void yourClass::Function()
{
    QPushButton* buttonSender = qobject_cast<QPushButton*>(sender()); // retrieve the button you have clicked
    QString buttonText = buttonSender->text(); // retrive the text from the button clicked
}

Upvotes: 13

Related Questions