在QObject :: findChild函数的qml-child-items中等效

时间:2018-07-31 12:13:30

标签: qt qml qquickitem

2允许您按类别和名称搜索子对象中的特定对象:

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

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

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

但是QQuickItem不存在该功能。
实现此目的最方便/最有效的方法是什么?

到目前为止,我只能想到T QObject::findChild列表上的循环。

1 个答案:

答案 0 :(得分: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);