'QML ListView sections not showing

I am trying to display a list of contacts in a ListView in QML. The list comes from the c++ side of my app and the contents are displaying just fine.

Now I want to be able to add sections from the name, but it doesn't work as I want.

What is weird is that the following code does work and shows the sections I want :

Working solution :

main.cpp :
    QList<QObject*> contactList;
    engine.rootContext()->setContextProperty("contactsModel", QVariant::fromValue(contactList));

contoller.cpp :
    ...
    // Call setContextProperty every time the list is updated
    m_qmlEngine->setContextProperty("contactsModel", QVariant::fromValue(m_currentUser->contactListObjects()));
    ...

qml file :
    ListView {
        id: contactListView
        model: contactsModel

        section {
            property: "name"
            criteria: ViewSection.FirstCharacter
            delegate: Rectangle {
                ...
            }
        }
    }

However, the way that i find more elegant only shows the data from the model, not the section headers :

main.cpp :
    Controller ctrl(engine.rootContext());
    engine.rootContext()->setContextProperty("Controller", &ctrl);

contoller.h :

class Controller : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QList<QObject*> contactListModel READ contactListModel NOTIFY contactListModelChanged)
...
};

qml file :
    ListView {
        id: contactListView
        model: Controller.contactListModel

        section {
            property: "name"
            criteria: ViewSection.FirstCharacter
            delegate: Rectangle {
                ...
            }
        }
    }

I find the second method more elegant because the data will be updated automatically from the signal that is emitted, whereas the first solution means I need to call the setContextProperty method each time.

I found a very similar question here, but unfortunately there are no answers.

What difference am I missing between the 2 solutions ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source