QML + QList<QObject*> not picked up in setContextProperty

188 views Asked by At

I'm attempting to do something akin to Using C++ Models with Qt Quick Views . Specifically I want a QList of QObject-derived instances to render in a QML ListView.

If I follow the examples exactly, it works.

However, if I attempt to acquire the model through a custom Session object set to context, I run into issues.

Specifically, the session code looks like:

class Session : public QObject
{
    Q_OBJECT

    typedef QVariant result_type;

    Q_PROPERTY(result_type items READ items NOTIFY itemsChanged)
...
};

Each of its items is a DataObject which has a name property

Then effectively we do a:

ListView {
    model: session.items

    delegate: Rectangle {
        required property string name
    }
}

and in main:

Session session;

QQmlContext* context = engine.rootContext();
context->setContextProperty("session", &session);

...

QList<QObject*> dataList;
session.setItems(dataList);

Everything yields a:

Required property was not initialized

despite verifying there is content in session.items. I use this kind of Session object for other QML things without incident.

What am I doing wrong?

EDIT:

As mention in comments, one can get to properties via modelData which is a functional workaround, but the initial question remains.

I didn't put the QML in here because it's kinda big, but here's a gist of it in its current form https://gist.github.com/malachib/ac05c535fd11c5d4961feade307d9102

1

There are 1 answers

3
dynerp On

As documentation says:

Required properties play a special role in model-view-delegate code: If the delegate of a view has required properties whose names match with the role names of the view's model, then those properties will be initialized with the model's corresponding values. For more information, visit the Models and Views in Qt Quick page.

So, if you have custom list in type of QList<Object*> where QObject is your object derived custom class here(instead of QAbstractItemModel derived one since the required values will be initalized as soon as they defined with the same name in the overridden rolenames function e.g. {"SomeRole", "someRole"} - required property string someRole), the defined required properties in the delegate will not be initialized with the default values of your custom class properties(also you can not directly set their values when defining them).