QML DefaultProperty for ObjectList / Repeater

I am extending QML with my own C ++ widget, DefaultProperty and QQmlListProperty , for example here .

So i can write

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

Child objects are added to a member property of type QQmlListProperty .

But when I want to use 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 to set the list property of my parent, which is a repeater?

EDIT: I found out that Repeater inherits Item and can only repeat elements. But my Child object inherits QObject . Therefore, I have to create Repeater for QObjects . But it's not a problem. How can an Item object have manually written child elements, as well as a repeater that gives it many children?

+5
source share
1 answer

Use the QObjectList Model

You say that your Child is QObjects, then you can use a QObjectList instead of your construct. Print a 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 for Parent as a model for the repeater, it will have access to all 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 } } 
0
source

Source: https://habr.com/ru/post/1237305/


All Articles