在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);
}
您可以通过parent
和objectName
获取按钮,在您的情况下,父母就是这样,因此您应该使用以下内容:
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");
}