Qt项目角色实现

问题描述:

如何实现Qt项目角色机制?只是一些存储在支持角色的类中的地图?Qt项目角色实现

项目角色用于检索给定模型索引的不同数据,例如,列表模型中的文本,图标,工具提示等。它们如何实施取决于模型。

QStandardItemModel实际上在内部使用QMap(角色到值)。

有关自定义模式,通常是一个使用if或switch语句,为不同的角色返回不同的数据:

QVector<SomeObject> m_data; 

QVariant SomeListModel::data(const QModelIndex& index, int role) const { 
    const SomeObject& so = m_data[index.row()]; 
    switch (role) { 
    case Qt::DisplayRole: 
     return so.name(); 
    case Qt::DecorationRole: 
     return so.icon(); 
    case Qt::ToolTipRole: 
     return so.details(); 
    case SomeObjectRole: // Custom role, SomeObjectRole=Qt::UserRole 
     return QVariant::fromValue<SomeObject>(so); 
    default: 
     break; 
    } 

    return QVariant(); 
} 

快速指数()和数据()方法是重要的是得到有效的模式,所以要避免地图查询以及与项目数量(此处为m_data的大小)相关的不是O(1)的其他所有内容。