Parent QML Replicator

Let's say I have two types of user elements: parent and child

And there may be more than one parent in the scene

A simple scene is as follows:

Parent {
    Child {
        id: child1
    }
    Child {
        id: child2
    }
}

After loading the scene, I want to initialize all the Children in Parent classes:

void InitializeChildren() {
    list = findChildren<Child*>(QString(),Qt::FindChildrenRecursively);
    foreach(Child * child,list) {
        InitChild(this,child);
}

But this is not with a more complex scene:

Parent {
    Rectangle {
        Repeater {
            model: 10
            delegate: Child {
            }
        }
    }    
}

just bacause The repeater has no children as children. So my question is: how can I get all Child objects if I know for sure that they are nested children of the specified parent?

+3
source share
2 answers

, : findChildren() , - findChildren() findChildren() Repeater findChildren() . qquickrepeater.cpp , Repeater QQuickItem::setParentItem() . , , "" .

TL;DR: findChildren() Qt5 . - :

void getAllSearchTypes(QQuickItem *parent, QList<SearchType *> &list) {

 QList<QQuickItem *> children = parent->childItems();   
  foreach (QQuickItem *item, children) {
    SearchType *searchObject = dynamic_cast<SearchType *>(item);
    if (seachObject) list.append(searchObject);
    // call recursively and browse through the whole scene graph
    getAllSearchTypes(item, list);
 } 
}

:

QList<SearchType *> list;
getAllSearchTypes(rootItem, list);
// list now contains all objects of type SearchType, recursively searched children of rootItem

SearchType C++, .

. findChildren() , childItems() children(). , QQuickItem , , findChildItems() Qt, .

+2

++:

Parent {
    Rectangle {
        Repeater {
            model: childModel
            delegate: Child {
                 Text { text: childValue }
            }
        }
    }    
}

++:

QList<QObject*> m_childModel;
void InitializeChildren() {
    this->m_childModel.append(new Child("value 1"));
    this->m_childModel.append(new Child("value 2"));
    this->m_scene->rootContext()->setContextProperty("childModel", QVariant::fromValue(m_childModel));
}

setContextProperty QML.

Child:

class Child : public QObject
{
    Q_OBJECT

public:
    Child(QString value) : m_value(value) {}
    Q_PROPERTY(QString  childValue    READ getChildValue  WRITE setChildValue    NOTIFY childValueUpdated)
    // Other properties... 

    QString getChildValue()    const { return m_value; }
    void setChildValue(const QString &value)
    {
        if (value == m_value)
            return;
        m_value = value;
        emit childValueUpdated();
    }

signals:
    void childValueUpdated();

private:
    QString m_value;

}
0

All Articles