#include "StatisticsListModel.h" // 函数作用:初始化统计结果列表模型。 StatisticsListModel::StatisticsListModel(QObject *parent) : QAbstractListModel(parent) { } // 函数作用:返回统计结果行数。 int StatisticsListModel::rowCount(const QModelIndex &parent) const { // QAbstractListModel 不使用树形子节点,有效 parent 返回 0 是 Qt 模型约定。 if (parent.isValid()) { return 0; } return m_items.size(); } // 函数作用:根据行号和 role 返回统计页需要显示的字段。 QVariant StatisticsListModel::data(const QModelIndex &index, int role) const { // 防御式边界检查,避免 QML 在模型重置瞬间读取到无效行。 if (!index.isValid() || index.row() < 0 || index.row() >= m_items.size()) { return {}; } const Item &item = m_items.at(index.row()); switch (role) { case StudentIdRole: return item.studentId; case NameRole: return item.name; case TotalCountRole: return item.totalCount; case TodayCountRole: return item.todayCount; case LastCheckInRole: return item.lastCheckIn; case AverageConfidenceRole: return item.averageConfidence; // 与记录表保持一致:内部保存 0~1,界面显示百分比。 case AverageConfidenceTextRole: return QString::number(item.averageConfidence * 100.0, 'f', 2) + "%"; default: return {}; } } // 函数作用:声明统计模型 role 与 QML 字段名之间的映射关系。 QHash StatisticsListModel::roleNames() const { return { {StudentIdRole, "studentId"}, {NameRole, "name"}, {TotalCountRole, "totalCount"}, {TodayCountRole, "todayCount"}, {LastCheckInRole, "lastCheckIn"}, {AverageConfidenceRole, "averageConfidence"}, {AverageConfidenceTextRole, "averageConfidenceText"} }; } // 函数作用:整体替换统计结果数据并通知 QML 刷新。 void StatisticsListModel::setItems(const QVector &items) { // 统计结果按日期区间整体重算,因此使用模型重置通知 QML 全量替换。 beginResetModel(); m_items = items; endResetModel(); }