Qt重新入坑(1)——项视图类学习(1)
QAbstractTableModel派生类总结
-
使用容器Map、List等容器存储数据;
-
必须实现rowCount、columnCount、data 3个纯虚函数;
-
rowCount的功能:
// 设置tableView的总行数 // 一般是容器的大小 int CurrencyModel::rowCount(const QModelIndex & /* parent */) const { return currencyMap.count(); } -
columnCount的功能:
// 设置tableView的总列数 // 一般是容器的大小或固定值 int CurrencyModel::columnCount(const QModelIndex & /* parent */) const { return 2; } -
data的功能:
// 根据ItemDataRole role的不同分类 // 从Model等,返回不同的值 QVariant CurrencyModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::TextAlignmentRole) { return int(Qt::AlignRight | Qt::AlignVCenter); } else if (role == Qt::DisplayRole) { QString rowCurrency = currencyAt(index.row()); QString columnCurrency = currencyAt(index.column()); if (currencyMap.value(rowCurrency) == 0.0) return "####"; double amount = currencyMap.value(columnCurrency) / currencyMap.value(rowCurrency); return QString("%1").arg(amount, 0, 'f', 4); } return QVariant(); } -
headerData的功能
// 设置tableView表头的内容 // 横向和纵向都可以设置 QVariant CurrencyModel::headerData(int section, Qt::Orientation /* orientation */, int role) const { if (role != Qt::DisplayRole) return QVariant(); return currencyAt(section); } -
flags的功能
// 设置tableView的item项 // 可选中、可编辑、可拖放等 Qt::ItemFlags TableModel::flags(const QModelIndex& index) const { if (!index.isValid()) return QAbstractItemModel::flags(index); Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; if (index.column() == CHECK_BOX_COLUMN) flags |= Qt::ItemIsUserCheckable; return flags; } -
setData的功能
// 根据不同的role值,设置Model的中的数据 bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; int nColumn = index.column(); FileRecord record = m_recordList.at(index.row()); switch (role) { case Qt::DisplayRole: { if (nColumn == File_PATH_COLUMN) { record.strFilePath = value.toString(); m_recordList.replace(index.row(), record); emit dataChanged(index, index); return true; } } case Qt::CheckStateRole: { if (nColumn == CHECK_BOX_COLUMN) { record.bChecked = (value.toInt() == Qt::Checked); m_recordList.replace(index.row(), record); emit dataChanged(index, index); return true; } } default: return false; } return false; }
QAbstractItemModel虚拟函数继承关系

QAbstractItemModel纯虚函数继承关系

posted on 2022-06-14 14:43 OctoberKey 阅读(85) 评论(0) 收藏 举报
浙公网安备 33010602011771号