代码之家  ›  专栏  ›  技术社区  ›  GeneCode

通过字符串获取小部件

  •  1
  • GeneCode  · 技术社区  · 7 年前

    在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);
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   eyllanesc Yonghwan Shin    7 年前

    你可以通过 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");
    }