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

I need to use some kind of C ++ qt model in qml. I already have a QStandardItemModel, but it does not work in QML due to the so-called setRoleNames (). I was looking for some explanation of the roles, but I seem to be unable to find. I found some solution for using QStandardItemMOdel in qml ( here ), but it uses "roles", so I donโ€™t understand how it works.

What are the roles in qt models?

+4
source share
1 answer

A role is simply an additional selector used when accessing model data. It depends on the model and the idea of โ€‹โ€‹how to specifically interpret the roles. When you use a model, you need to decide which roles to use to maintain the modelโ€™s behavior. Roles allow you to add different attributes to each data item.

Let's look at a specific example. 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 any role, and the role itself will be indicated by the dataChanged() signal. You can access the string using either a role. It is designed and intended to be used to break the binding chains.

The role name is displayed as a property of the model. For instance. if you want to associate the TextEdit in the delegate with the model, you can do the following:

 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 ++ element models provided by Qt define the display and editing of roles by name. If you have a custom model and want to provide other names, in Qt 5 you must override QAbstractItemModel::roleNames() to return the hash. Of course, the hash must contain the roles display and edit ! In Qt 4, you need to use setRoleNames() , and roleNames() not virtual.

I presented a complete example in another answer .

+4
source

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


All Articles