File indexing completed on 2024-05-19 05:44:23

0001 /*
0002     SPDX-FileCopyrightText: 2016-2019 Milian Wolff <mail@milianw.de>
0003 
0004     SPDX-License-Identifier: LGPL-2.1-or-later
0005 */
0006 
0007 #include "costdelegate.h"
0008 
0009 #include <QDebug>
0010 #include <QPainter>
0011 
0012 #include <cmath>
0013 
0014 CostDelegate::CostDelegate(int sortRole, int maxCostRole, QObject* parent)
0015     : QStyledItemDelegate(parent)
0016     , m_sortRole(sortRole)
0017     , m_maxCostRole(maxCostRole)
0018 {
0019 }
0020 
0021 CostDelegate::~CostDelegate() = default;
0022 
0023 void CostDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
0024 {
0025     // TODO: handle negative values
0026     const int64_t cost = index.data(m_sortRole).toULongLong();
0027     if (cost == 0) {
0028         QStyledItemDelegate::paint(painter, option, index);
0029         return;
0030     }
0031 
0032     const int64_t maxCost = index.data(m_maxCostRole).toULongLong();
0033     // top-down can miscalculate the peak cost
0034     const auto fraction = std::min(1.f, std::abs(float(cost) / maxCost));
0035     auto rect = option.rect;
0036     rect.setWidth(rect.width() * fraction);
0037 
0038     const auto& brush = painter->brush();
0039     const auto& pen = painter->pen();
0040 
0041     painter->setPen(Qt::NoPen);
0042 
0043     if (option.features & QStyleOptionViewItem::Alternate) {
0044         // we must handle this ourselves as otherwise the custom background
0045         // would get painted over with the alternate background color
0046         painter->setBrush(option.palette.alternateBase());
0047         painter->drawRect(option.rect);
0048     }
0049 
0050     auto color = QColor::fromHsv(120 - fraction * 120, 255, 255, (-((fraction - 1) * (fraction - 1))) * 120 + 120);
0051     painter->setBrush(color);
0052     painter->drawRect(rect);
0053 
0054     painter->setBrush(brush);
0055     painter->setPen(pen);
0056 
0057     if (option.features & QStyleOptionViewItem::Alternate) {
0058         auto o = option;
0059         o.features &= ~QStyleOptionViewItem::Alternate;
0060         QStyledItemDelegate::paint(painter, o, index);
0061     } else {
0062         QStyledItemDelegate::paint(painter, option, index);
0063     }
0064 }
0065 
0066 #include "moc_costdelegate.cpp"