c++ - 我应该使用多个角色还是一个将实际属性推迟到 QObject 包装/公开数据作为其属性
问题描述
是QAbstractListModel
具有说角色的实现
name, image, enabled, color, editable
比具有单一角色的实现更好(请原谅我无法想出更好的名称)
thing
这会导致QObject*
带有上述Q_PROPERTY
s 的 a 被返回?
在访问委托中的值时,QML 方面的区别将是一个额外的“间接”:
model.thing.name
对比
model.name
我倾向于 QObject 方法,因为它将数据视图与列表模型分开,并且具有重用的潜力。它也不需要您也实现该setData
功能。据我所知,“许多角色”选项没有特定的专业人士,除非当然不可能正确定义QObject
包装数据的适当子类(因为例如,对于特定情况,它在概念上几乎没有意义)。
解决方案
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.
推荐阅读
- java - Azure IoTHub DeviceMessage,消息正文上的路由过滤器不起作用
- html - 在 D365 FO HTML 查看器中使用 CSS
- javascript - 启用 Adblock 时 Twitter 转换不起作用
- c++ - 如何在 x64 上制作“堆栈溢出”异常
- scala - Akka 演员没有收到案例类 [Akka 远程处理](序列化问题)
- android - 如何使解析后的颜色变浅?
- python - 如何在 Python 中解析非英语混合文本
- sql - 如何从 SQL Server 的几行中获取值最小的列的名称?
- c++ - 静态库缺少 `__imp_` 符号
- embedded-linux - PCIe PIC_INTERRUPT_PIN (0x3c) 为 0