File indexing completed on 2024-05-05 16:16:40

0001 /*
0002  * This file is part of KQuickCharts
0003  * SPDX-FileCopyrightText: 2019 Marco Martin <mart@kde.org>
0004  * SPDX-FileCopyrightText: 2019 David Edmundson <davidedmundson@kde.org>
0005  * SPDX-FileCopyrightText: 2019 Arjen Hiemstra <ahiemstra@heimr.nl>
0006  *
0007  * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0008  */
0009 
0010 #include "ColorGradientSource.h"
0011 
0012 #include <QVariant>
0013 
0014 #include <QDebug>
0015 
0016 ColorGradientSource::ColorGradientSource(QObject *parent)
0017     : ChartDataSource(parent)
0018 {
0019 }
0020 
0021 int ColorGradientSource::itemCount() const
0022 {
0023     return m_itemCount;
0024 }
0025 
0026 QVariant ColorGradientSource::item(int index) const
0027 {
0028     if (index < 0 || index >= m_colors.size()) {
0029         return QVariant{};
0030     }
0031 
0032     return m_colors.at(index);
0033 }
0034 
0035 QVariant ColorGradientSource::minimum() const
0036 {
0037     return QVariant{};
0038 }
0039 
0040 QVariant ColorGradientSource::maximum() const
0041 {
0042     return QVariant{};
0043 }
0044 
0045 QColor ColorGradientSource::baseColor() const
0046 {
0047     return m_baseColor;
0048 }
0049 
0050 void ColorGradientSource::setBaseColor(const QColor &newBaseColor)
0051 {
0052     if (newBaseColor == m_baseColor) {
0053         return;
0054     }
0055 
0056     m_baseColor = newBaseColor;
0057     regenerateColors();
0058     Q_EMIT baseColorChanged();
0059 }
0060 
0061 void ColorGradientSource::setItemCount(int newItemCount)
0062 {
0063     if (newItemCount == m_itemCount) {
0064         return;
0065     }
0066 
0067     m_itemCount = newItemCount;
0068     regenerateColors();
0069     Q_EMIT itemCountChanged();
0070 }
0071 
0072 QVariantList ColorGradientSource::colors() const
0073 {
0074     QVariantList colorsVariant;
0075     colorsVariant.reserve(m_colors.count());
0076     for (const QColor &color : std::as_const(m_colors)) {
0077         colorsVariant.append(color);
0078     }
0079     return colorsVariant;
0080 }
0081 
0082 void ColorGradientSource::regenerateColors()
0083 {
0084     if (!m_baseColor.isValid() || m_itemCount <= 0) {
0085         return;
0086     }
0087 
0088     m_colors.clear();
0089 
0090     for (int i = 0; i < m_itemCount; ++i) {
0091         auto newHue = m_baseColor.hsvHueF() + i * (1.0 / m_itemCount);
0092         newHue = newHue - int(newHue);
0093         m_colors.append(QColor::fromHsvF(newHue, m_baseColor.saturationF(), m_baseColor.valueF(), m_baseColor.alphaF()));
0094     }
0095 
0096     Q_EMIT dataChanged();
0097 }
0098 
0099 #include "moc_ColorGradientSource.cpp"