首页 > 解决方案 > 我应该使用多个角色还是一个将实际属性推迟到 QObject 包装/公开数据作为其属性

问题描述

QAbstractListModel具有说角色的实现

name, image, enabled, color, editable

比具有单一角色的实现更好(请原谅我无法想出更好的名称)

thing

这会导致QObject*带有上述Q_PROPERTYs 的 a 被返回?

在访问委托中的值时,QML 方面的区别将是一个额外的“间接”:

model.thing.name

对比

model.name

我倾向于 QObject 方法,因为它将数据视图与列表模型分开,并且具有重用的潜力。它也不需要您也实现该setData功能。据我所知,“许多角色”选项没有特定的专业人士,除非当然不可能正确定义QObject包装数据的适当子类(因为例如,对于特定情况,它在概念上几乎没有意义)。

标签: c++qtqmlqabstractitemmodelqabstractlistmodel

解决方案


Having roles in a model is helpful when you want to use it with features that rely on roles.

For example you want to feed your model to a ComboBox, if it has roles you can just specify a textRole to the ComboBox and it will do its thing. If using a single object role, you will have to modify the delegate to display your correct object property. Roles are also needed if you want to make use of ListView's section feature.

Like @derm said, it's also useful with a QSortFilterProxyModel (shameless plug: if your model has roles, it's super easy to filter or sort it with my SortFilterProxyModel library).

You mention reusability and having to reimplement stuff. That's a good point but it's totally doable to have a generic model with roles based on QObject properties. In fact it has been done and it is available with a very permissible license here : Thomas Boutroue's QQmlObjectListModel. From c++ it has the same API as a QList but it exposes a QAbstractListModel that is usable by QML. The roles are based on the properties of your objects, and when a notify signal is emitted, it emits the corresponding dataChanged signal. insertRows and friends are also handled automatically.

With that said, I don't see much point in doing a model with a single object role. If you want a proper model with rowsInserted/rowRemoved signals (and you should, unless you just have a static model, in this case a QVariantList or a QObjectList is enough), you'd have to implement it yourself anyway when you can just use QQmlObjectListModel and be done with it.


推荐阅读