Qt之获取子部件

Qt5.10

    QList list_children = this->children();
    for(int i=0;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(child);
 
   
           if(p_edit)
           {
               p_edit->setText("test");
           }
 
   
 
   
       }
    }

后记:

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

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

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

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


转载于:https://www.cnblogs.com/zhangxuan/p/9356097.html

你可能感兴趣的:(Qt之获取子部件)