Search code examples
c++qtqmlroles

What are roles in qt model and what does setRoleNames() do?


I have to use some kind of c++ qt model in qml. I already have QStandardItemModel but it does not work in QML because of so called setRoleNames(). I have been looking for some explanation of roles but I cannot seem to find. I have found some kind of solution of using QStandardItemMOdel in qml (here) but it uses "roles", so I do not understand how it works.

What are roles in qt models?


Solution

  • A role is simply an additional selector used when accessing data of a model. It's up to the model and the view as to how specifically to interpret the roles. When you use the model, you have to decide what roles to use keeping model's behavior in mind. The roles let you attach various attributes to each data item.

    Let's look at a concrete example. The QStringListModel ignores all roles but EditRole and DisplayRole. If you use any other role, the data access operation is ignored. You can set the string using either role, and the very role used will be indicated by the dataChanged() signal. You can access the string using either role. This is by design and is meant to be usable to break binding chains.

    A role's name is exposed as a property of the model. E.g. if you want to bind a TextEdit in a delegate to the model, you could do as follows:

    delegate: Component {
        TextInput {
            id: editor
            text: edit // show the "edit" role of the model, to break the binding loop
            onTextChanged: model.display = text // set the display role of the model
        }
    }
    

    The C++ item models provided by Qt define the display and edit roles by name. If you have a custom model and want to provide other names, in Qt 5 you should reimplement QAbstractItemModel::roleNames() to return a hash. Said hash should contain the display and edit roles, of course! In Qt 4, you need to use setRoleNames() instead, as roleNames() is not virtual.

    I've provided a complete example in another answer.