2

问题在标题中。我在文档中找不到任何明显的建议这样做的方法。我必须使用递归子查找方法并顺序测试每个子的父指针以过滤掉非直接子吗?

顺便说一句,文档似乎指的是“直系祖先”,我认为它的意思是“直系后代”。

(编辑:我正在寻找简单,所以答案不必使用该findChild()方法。)

4

4 回答 4

8

我在 Qt 5 中为QObject::findChild()添加了一个标志,称为,它允许您完全执行此操作。Qt::FindDirectChildOnly

所以这个问题很快就会成为过去的问题:-)

于 2012-02-23T17:48:07.583 回答
4
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;
}

一个模板版本,将根据具有可选名称的类型进行过滤。根据 TheHorse 的回答。

于 2012-01-05T14:53:19.420 回答
0
QObject* find(QObject* parent, const QString& objName)
{
    foreach (QObject* child, parent->children())
    {
        if (child->objectName() == objName)
        {
            return child;
        }
    }
    return 0;
}
于 2012-01-05T10:59:41.110 回答
0

根据skyhisi给出的答案,确切的答案将如下实现,更符合我的需求。

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;
}
于 2012-01-06T11:14:46.823 回答