【问题标题】:Getting a widget by string通过字符串获取小部件
【发布时间】:2017-09-13 08:31:13
【问题描述】:

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

【问题讨论】:

  • 你是如何创建按钮的?
  • 嗨@eyllanesc。我在循环中以编程方式创建它,并用循环变量分配它们的名称。
  • 您是否将父级传递给按钮?
  • 我将它们添加到布局中。这会自动为他们分配父母吗?
  • 您可以证明您已经创建了它,以便更好地了解您并为您提供合适的解决方案。

标签: c++ qt variables qt5 qstring


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多