1

In a for loop, I can construct a string.

foreach (...) {
  QString str = "pushButton" + QString::number(count);
  // this gives pushButton1

  // Now I want to get the button widget that has this string as it's variable name 
  // and modify it in some way, e.g. change it's button caption

  str->setText("New Title");

  count ++;
}

Is this possible? if so, then how

edited: here's how i created the buttons

for (int i=0; i<total; i++) {
    QPushButton *btn = new QPushButton();
    btn->setObjectName("pushButton" + QString::number(i));
    ui->horizontalLayout->addWidget(btn);
}
6
  • How did you create the buttons? Commented Sep 13, 2017 at 8:37
  • Hi @eyllanesc. I created it programatically in a loop and have their names assigned with the loop variable. Commented Sep 13, 2017 at 8:39
  • Have you passed a parent to the buttons? Commented Sep 13, 2017 at 8:39
  • i added them to a layout. does that automatically assign them a parent? Commented Sep 13, 2017 at 8:40
  • You can show you have created it to understand you better and give you an appropriate solution. Commented Sep 13, 2017 at 8:41

1 Answer 1

4

You can get the button through the parent and objectName, in your case the parent is this, so you should use the following:

QWidget* p =  ui->horizontalLayout->parentWidget();

for(int count=0; count<total; count++){
    const QString str = "pushButton" + QString::number(count);
    QPushButton* btn = p->findChild<QPushButton *>(str);
    btn->setText("someText");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.