6
votes

I'm extending QML with my own widget from c++, with DefaultProperty and QQmlListProperty, like here.

So that I can write

Parent {    
    Child { prop: "ch1" }
    Child { prop: "ch2" }
    Child { prop: "ch3" }
}

The Child objects are appending to a member property of type QQmlListProperty.

But when I want to use a Repeater like this:

Parent {
    Repeater {
        model: ["ch1","ch2","ch3"]
        delegate: Child {
            prop: modelData
        }
    }
}

Then the runtime gives me an error: Cannot assign object to list property "childObjects"

How can I set the list property of my Parent object which a Repeater?

EDIT: I've found out, that the Repeater inherits Item and can repeat only Items. But my Child object inherits QObject. So I must create a Repeater for QObjects. But that isn't the problem. How can the Item object have a manually written child items, and also a Repeater child which gives him many children?

1
You're right, Repeater used for visual items only. But you can create Child objects with Qt.createComponent() in loop. Or implement such functionality as Repeater with C++ extension. - folibis
@folibis you're right, but creating my own repeater is difficult, if not impossible. I'm looking in qt code, and the Repeater class has so many private members, and uses classes that are not publicly available ... - microo8
Ok, then use Qt.createComponent() in loop. All you need, as I understand is creating a component and assigning it to Parent. - folibis

1 Answers

0
votes

Use a QObjectList Model

You say your Child are QObjects, then you can use a QObjectList instead of your construct. Expose the list with something similar to:

class Parent : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QList<QObject*> elements READ ...  WRITE ... NOTIFY ...)
}

class Child : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString something READ ...  WRITE ... NOTIFY ...)
    Q_PROPERTY(int     myValue   READ ...  WRITE ... NOTIFY ...)
    ...
}

Then you use the elements property of Parent as a model for the repeater, it will have access to all of the properties (Q_PROPERTIES) of the Child elements.

Parent {
    id: main
}
Repeater {
    model: main.elements
    delegate: Whatever { // will create one for each element
        prop: something
        prop2: myValue
    }
 }