diff --git a/src/ui/models/EmailTreeModel.cpp b/src/ui/models/EmailTreeModel.cpp index cbb4d52..ba76a56 100644 --- a/src/ui/models/EmailTreeModel.cpp +++ b/src/ui/models/EmailTreeModel.cpp @@ -251,31 +251,55 @@ void EmailTreeModel::buildGroups() return dateA > dateB; }); - // Group by date - QMap> groups; // groupName -> mail indices + // Group by date - store both groupName and representative date for sorting + struct GroupData { + QString name; + QDateTime representativeDate; // earliest date in group for sorting + QVector mailIndices; + }; + QMap groupsMap; + for (int idx : indices) { if (idx < 0 || idx >= m_emails.size()) continue; const QDateTime& dt = m_emails[idx].date(); if (!dt.isValid()) continue; QString groupName = groupNameForDate(dt); - groups[groupName].append(idx); + auto& g = groupsMap[groupName]; + g.name = groupName; + g.mailIndices.append(idx); + // Keep the earliest (most recent) date as representative for sorting groups chronologically + if (!g.representativeDate.isValid() || dt > g.representativeDate) { + g.representativeDate = dt; + } } - // Create tree items in group order - int groupIdx = 0; - for (auto it = groups.constBegin(); it != groups.constEnd(); ++it) { - const QString& groupName = it.key(); - const QVector& mailIndices = it.value(); - if (mailIndices.isEmpty()) continue; + // Sort groups by representative date descending (newest group first) + QVector sortedGroups; + sortedGroups.reserve(groupsMap.size()); + for (auto it = groupsMap.constBegin(); it != groupsMap.constEnd(); ++it) { + if (!it.value().mailIndices.isEmpty()) { + sortedGroups.append(it.value()); + } + } + std::sort(sortedGroups.begin(), sortedGroups.end(), [](const GroupData& a, const GroupData& b) { + // Newest group first (descending by representative date) + if (!a.representativeDate.isValid() && !b.representativeDate.isValid()) return false; + if (!a.representativeDate.isValid()) return false; + if (!b.representativeDate.isValid()) return true; + return a.representativeDate > b.representativeDate; + }); + // Create tree items in chronological group order + int groupIdx = 0; + for (const GroupData& g : sortedGroups) { TreeItem* groupItem = new TreeItem(TreeItem::Group, m_rootItem); - groupItem->groupName = groupName; + groupItem->groupName = g.name; groupItem->groupIndex = groupIdx++; groupItem->row = m_rootItem->children.size(); m_rootItem->children.append(groupItem); - for (int mailIdx : mailIndices) { + for (int mailIdx : g.mailIndices) { if (mailIdx < 0 || mailIdx >= m_emails.size()) continue; TreeItem* mailItem = new TreeItem(TreeItem::Mail, groupItem); mailItem->mailIndex = mailIdx;