2013-01-13 56 views

回答

1

項目角色用於檢索給定模型索引的不同數據,例如,列表模型中的文本,圖標,工具提示等。它們如何實施取決於模型。

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)的其他所有內容。