'Is there a simple way of limiting QObject::findChild() to direct children only?
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.)
Solution 1:[1]
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.
Solution 2:[2]
QObject* find(QObject* parent, const QString& objName)
{
foreach (QObject* child, parent->children())
{
if (child->objectName() == objName)
{
return child;
}
}
return 0;
}
Solution 3:[3]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silas Parker |
| Solution 2 | TheHorse |
| Solution 3 | Community |
