1

T QObject::findChild允许您按类和名称在子项中搜索特定对象:

QPushButton *button = parentWidget->findChild<QPushButton*>("button1",
                                                Qt::FindDirectChildrenOnly);

我需要按类和名称找到这样的子项。就像是

MyQQuickItem *item = parentItem->findChildItem<MyQQuickItem*>("item1");

但该函数不存在QQuickItem
实现这一目标的最方便/有效的方法是什么?

到目前为止,我只能考虑QQuickItem::childItems列表中的一个循环。

4

1 回答 1

1

应该实现类似的逻辑,如下所示:

void FindChildren_helper(const QQuickItem *parent, const QString &name, const QMetaObject &mo, QList<void*> *list, Qt::FindChildOptions options)
{
    if (!parent || !list)
        return;
    const QList<QQuickItem *> &children = parent->childItems();
    QQuickItem *obj;
    for (int i = 0; i < children.size(); ++i) {
        obj = children.at(i);
        if(mo.cast(obj)){
            if (name.isNull() || obj->objectName() == name)
                list->append(obj);
        }
        if (options & Qt::FindChildrenRecursively)
            FindChildren_helper(obj, name, mo, list, options);
    }
}

void FindChildren_helper(const QQuickItem *parent, const QRegularExpression &re, const QMetaObject &mo, QList<void*> *list, Qt::FindChildOptions options)
{
    if (!parent || !list)
        return;
    const QList<QQuickItem *> &children = parent->childItems();
    QQuickItem *obj;
    for (int i = 0; i < children.size(); ++i) {
        obj = children.at(i);
        if(mo.cast(obj)){
            QRegularExpressionMatch m = re.match(obj->objectName());
            if (m.hasMatch())
                list->append(obj);
        }
        if (options & Qt::FindChildrenRecursively)
            FindChildren_helper(obj, re, mo, list, options);
    }
}

template<typename T> QList<T> findChildren(QQuickItem *parent, const QString &aName = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively)
{
    typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type ObjType;
    QList<T> list;
    FindChildren_helper(parent, aName, ObjType::staticMetaObject, reinterpret_cast<QList<void *> *>(&list), options);
    return list;
}


template<typename T> QList<T> findChildren(QQuickItem *parent, const QRegularExpression &re, Qt::FindChildOptions options = Qt::FindChildrenRecursively)
{
    typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type ObjType;
    QList<T> list;
    FindChildren_helper(parent, re, ObjType::staticMetaObject, reinterpret_cast<QList<void *> *>(&list), options);
    return list;
}

例子:

QList<QQuickItem *> childs = findChildren<QQuickItem *>(parentItem, "somename", Qt::FindDirectChildrenOnly);
于 2018-07-31T13:06:32.737 回答