Is there a simple way of limiting QObject::findChild() to direct children only?

5.8k Views Asked by At

Question is in the title. I can't find anything obvious in the documentation which suggests a way of doing this. Must I use the recursive children finding methods and test each child's parent pointer sequentially to filter out the non-direct children?

Incidentally, the documentation seems to refer to "direct ancestor"s by which I think it means "direct descendant".

(edit: I'm looking for simplicity, so the answer doesn't have to use the findChild() method.)

4

There are 4 best solutions below

1
On BEST ANSWER

I have added a flag to QObject::findChild() in Qt 5, called Qt::FindDirectChildOnly, which allows you to do exactly this.

So this issue will soon be a problem of the past :-)

1
On
QObject* find(QObject* parent, const QString& objName)
{
    foreach (QObject* child, parent->children())
    {
        if (child->objectName() == objName)
        {
            return child;
        }
    }
    return 0;
}
0
On
template <class T>
T findDirectChild(const QObject* parent, const QString& name = QString())
{
    foreach (QObject* child, parent->children())
    {
        T temp = qobject_cast<T>(child);
        if (temp && (name.isNull() || name == child->objectName()))
            return temp;
    }
    return 0;
}

A template version that will filter based on type with optional name. Based on answer by TheHorse.

3
On

Based on the answer given by skyhisi the exact answer would be implemented as follows, which more closely meets my needs.

ChildClass const * ParentClass::_getPointerToDirectChild() const
{
    QObjectList allDirectChildren = this->children();
    QObject * anObject = 0;
    ChildClass const * aChild = 0;

    while (allDirectChildren.isEmpty() == false)
    {
        anObject = allDirectChildren.takeFirst();
        aChild = qobject_cast<ChildClass *>(anObject);
        if (aChild) return aChild;
    }

    return aChild;
}