Qt之获取子部件

Qt5.10

    QList<QObject*> list_children = this->children();
    for(int i=0;i<list_children.size();i++)
    {
       QObject *child =  list_children.at(i);

       QString object_name = child->objectName();
    //找到对象名称为lineEdit的控件
       if(object_name == QString("lineEdit"))
    {
       //强制类型装换,将 QObject* 转换为QLineEdit*
           QLineEdit *p_edit = dynamic_cast<QLineEdit*>(child);

           if(p_edit)
           {
               p_edit->setText("test");
           }


       }
    }

后记:

c++强制类型转换详解可参照:https://www.cnblogs.com/Allen-rg/p/6999360.html

Qt帮助文档中直接根据控件名称获取部件的方法:
QPushButton *button = parentWidget->findChild<QPushButton *>("button1");

帮助文档中还有许多详细介绍,帮助我们快读找到想要获取的部件,例如:

This example returns all QPushButtons that are children of parentWidget:
QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();


原文地址:https://www.cnblogs.com/zhangxuan/p/9356097.html