8

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?

1

1 Answer 1

13

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
}
2
  • Thanks for reply but I used it and It shows me this error: cannot resolve overloaded function 'qobject_cast' based on conversion to type 'QPushButton*' QPushButton* buttonSender = qobject_cast<QPushButton*>sender();
    – MHM
    Jun 21, 2016 at 8:08
  • 1
    @MHM Edited. Missing two parenthesis around sender()
    – IAmInPLS
    Jun 21, 2016 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.