laurapons
laurapons

Reputation: 1093

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!

Upvotes: 3

Views: 5109

Answers (2)

p-a-o-l-o
p-a-o-l-o

Reputation: 10047

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");

Upvotes: 6

Mohammad Kanan
Mohammad Kanan

Reputation: 4582

Use findChildren() along with objectName().contains() , for example:

QList<QWidget*> subwidgets = this->findChildren<QWidget*>();
QListIterator<QWidget*> it(subwidgets); // iterate through the list of widgets
QWidget *awiget;

while (it.hasNext()) {
    awiget = it.next(); // take each widget in the list
    if (awiget->objectName().contains("name")){
        qDebug() << awiget->objectName();
    }
}

Upvotes: 2

Related Questions