通过字符串获取小部件

Getting a widget by string

在for循环中,我可以构造一个字符串。

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 ++;
}

这可能吗?如果是这样,那么如何

已编辑:这是我创建按钮的方式

for (int i=0; i<total; i++) {
    QPushButton *btn = new QPushButton();
    btn->setObjectName("pushButton" + QString::number(i));
    ui->horizontalLayout->addWidget(btn);
}

你可以通过parentobjectName获取按钮,你的父级就是这个,所以你应该使用下面的:

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");
}