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?
To find out which button is the currently checked button, you can invoke the methods QButtonGroup. checkedButton() and QButtonGroup. checkedId() . The former will return a QButton object and the latter will return an index int , corresponding to the order in which the buttons were added to the group.
There is a signal clicked() that you could use to detect clicks. You can use pressed() or clicked() signals with custom slots.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With