Search code examples
c++qtfindqwidget

QWidget findChildren when objectname contains a specific string


How do you list all childs from a qwidget that contain a specific string inside de objectname?

For example, if I have:

 "general_widget", with children:
    "label_name_1"
    "label__1"
    "label_name_2"
    "label_id_2"
    "label_name_3"
    "label_id_3"
    "label_name_4"
    "label_id_4"

I would like to get a list of all children that contain "name" as part of the objectName, and another list with all children that contain "id". Thanks!


Solution

  • Have a simple function like this:

    QList<QWidget *> widgets(QWidget * parent, QString search)
    {
        QRegularExpression exp(search);
        return parent->findChildren<QWidget *>(exp);
    }
    

    and given a QWidget * widget you can call it this way:

    auto name_list = widgets(widget, "name");
    auto id_list = widgets(widget, "id");