Files
BionxControl/bcvaluedelegate.cpp
2026-03-31 18:18:37 +02:00

408 lines
11 KiB
C++

/***************************************************************************
BionxControl
© 2025 -2026 christoph holzheuer
christoph.holzheuer@gmail.com
Using:
mhs_can_drv.c
© 2011 - 2023 by MHS-Elektronik GmbH & Co. KG, Germany
Klaus Demlehner, klaus@mhs-elektronik.de
@see www.mhs-elektronik.de
Based on Bionx data type descriptions from:
BigXionFlasher USB V 0.2.4 rev. 97
© 2011-2013 by Thomas Koenig <info@bigxionflasher.org>
@see www.bigxionflasher.org
Bionx Bike Info
© 2018 Thorsten Schmidt (tschmidt@ts-soft.de)
@see www.ts-soft.de
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
@see https://github.com/bikemike/bionx-bikeinfo
***************************************************************************/
#include <QSlider>
#include <QLabel>
#include <QHBoxLayout>
#include <QWidget>
#include <QDebug>
#include <QPainter>
#include <QTimer>
#include <QVariantAnimation>
#include <QPropertyAnimation>
#include <QPainter>
#include <bcdeviceview.h>
#include <bcvaluedelegate.h>
#include <bcvalueslider.h>
#include <bctoggleswitch.h>
BCValueDelegate::BCValueDelegate(const BCValueList& valueList, BCDeviceView* view)
: QStyledItemDelegate{view}, _valueList{valueList}, _view{view}
{
}
QWidget* BCValueDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex& index) const
{
Q_UNUSED(option)
Q_UNUSED(index)
const BCValue& bcValue = *(_valueList[ index.row() ].get());
//qDebug() << " --- Create Editor: " << bcValue.label() << " value: " << params.value << " min: " << params.min << " max: " << params.max << " ratio:" << bcValue.calcMinMaxRatio()*100.0 << '%';
if( bcValue.isBoolean() )
{
auto* toogleSwitch = new BCToggleSwitch{parent};
return toogleSwitch;
}
BCValue::ValueRange params;
bool hasData = bcValue.hasValuesForSlider( params );
if( !hasData )
return nullptr;
auto* valueSlider = new BCValueSlider{parent};
valueSlider->setValueAndRange( params );
// Signal für sofortige Updates
connect(valueSlider, &BCValueSlider::valueChanged, this, [this, valueSlider]()
{
// Commit data sofort bei Änderung
emit const_cast<BCValueDelegate*>(this)->commitData(valueSlider);
});
// Signal für sofortige Updates
connect(valueSlider, &BCValueSlider::valueCommited, this, [this, valueSlider](int newValue)
{
qDebug() << " --- value set:" << newValue;
// Commit data sofort bei Änderung
emit const_cast<BCValueDelegate*>(this)->commitData(valueSlider);
});
return valueSlider;
}
void BCValueDelegate::setEditorData(QWidget *editor, const QModelIndex& index) const
{
Q_UNUSED(editor)
Q_UNUSED(index)
// tue nix.
}
void BCValueDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
Q_UNUSED(index)
const BCValue& bcValue = *(_valueList[ index.row()].get());
QRect editorRect;
if( !bcValue.isBoolean())
{
editorRect = clipToSliderRect( option.rect );
}
else
{
editorRect = option.rect.adjusted(option.rect.width() - cTextBlockOffset,4,0,0);
}
editor->setGeometry(editorRect);
}
void BCValueDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex& index) const
{
if( index.column() == 1)
{
// Daten vom Editor zurück ins Model speichern (Beim Schließen)
BCValueSlider* slider = qobject_cast<BCValueSlider*>(editor);
if (slider)
{
int value = slider->value();
model->setData(index, value, Qt::EditRole);
}
return;
}
QStyledItemDelegate::setModelData(editor, model, index);
}
void BCValueDelegate::paint(QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
int row = index.row();
if( index.column() != 1 || row<0 || row >= _valueList.size() )
return;
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
const BCValue& bcValue = *(_valueList[ index.row()].get());
if( bcValue.isBoolean() )
{
paintBooleanValue( painter, opt, bcValue );
}
else
{
// Standard-Zeichnen (Text, Hintergrund, Selection) durchführen
QStyledItemDelegate::paint(painter, opt, index);
}
if( !bcValue.isReadOnly() )
{
// Wir zeichnen boolean Values an toggle switches
if (bcValue.isBoolean())
{
//paintPlainToggleSwitch(painter, opt, bcValue);
}
else
{
paintPlainSliderIndicator(painter, opt.rect, bcValue.calcMinMaxRatio());
}
}
if(_rowOpacities.contains(row))
paintHighlightRow(painter, opt,index.row());
}
void BCValueDelegate::paintBooleanValue( QPainter *painter, const QStyleOptionViewItem& option, const BCValue& bcValue ) const
{
QRect textRect = option.rect.adjusted( 2,0,0,0);
// 3. Den tatsächlichen Wert aus dem Model auslesen
QString text = bcValue.rawValue() == 1 ? BCTags::Yes : BCTags::No;
// 3. Die korrekte Textfarbe ermitteln (extrem wichtig für die UX!)
// Wenn die Zeile markiert ist (Selected), muss der Text meist weiß sein,
// ansonsten schwarz (oder je nach System-Theme).
QPalette::ColorRole textRole = (option.state & QStyle::State_Selected)
? QPalette::HighlightedText
: QPalette::Text;
// 4. Den Text nativ durch den Style zeichnen lassen
QApplication::style()->drawItemText(
painter,
textRect,
Qt::AlignLeft | Qt::AlignVCenter, // Ausrichtung innerhalb von textRect
option.palette, // Farbpalette der View übernehmen
option.state & QStyle::State_Enabled, // Prüfen, ob die Zelle klickbar/aktiv ist
text, // Der zu zeichnende String
textRole // Die ermittelte Farb-Rolle
);
return;
/*
// 1. Standard-Optionen für die Zelle holen
QStyleOptionViewItem opt = option;
//initStyleOption(&opt, index);
// 2. Den originalen Text ('0' oder '1') ausblenden, damit er nicht hinter der Checkbox steht
opt.text = "";
// Zuerst den Hintergrund der Zelle zeichnen (wichtig für Selektions-Farben etc.)
// Wir übergeben nullptr für das Widget, da QStyledItemDelegate ohnehin unabhängig zeichnet
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter, nullptr);
// 4. Optionen für die Checkbox konfigurieren
QStyleOptionButton cbOpt;
cbOpt.state = isChecked ? QStyle::State_On : QStyle::State_Off;
cbOpt.state |= QStyle::State_Enabled; // Damit die Checkbox nicht ausgegraut/deaktiviert aussieht
// 5. Größe und Position berechnen (Zentriert in der Zelle)
// Wir fragen das System nach der korrekten Größe für eine Checkbox
QRect checkRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &cbOpt, nullptr);
// Checkbox exakt in der Mitte des zur Verfügung stehenden Zellenbereichs platzieren
cbOpt.rect = QStyle::alignedRect(option.direction, Qt::AlignLeft| Qt::AlignVCenter, checkRect.size(), option.rect);
// 6. Die native Checkbox zeichnen
QApplication::style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &cbOpt, painter, nullptr);
*/
}
QRect BCValueDelegate::clipToSliderRect( const QRect& rect, int buttonOffset ) const
{
return rect.adjusted
(
rect.width() - cTextBlockOffset, // Von rechts: cTextBlockOffset (==130) px (Breite der Progress Bar)
0, // Oben: kein Offset
-buttonOffset, // Rechts: 8px Padding
0 // Unten: kein Offset
);
}
/**
* @brief Zeichnet der 'Sliderindicator', also den Anteil des Gesamtwerts als Fortschrittsbalken
*/
void BCValueDelegate::paintPlainSliderIndicator(QPainter* painter, const QRect& rect, double ratio )const
{
QRect sliderRect = clipToSliderRect( rect, 35 );
//BCValueSliderOld::paintSliderIndicator(painter, sliderRect, ratio );
// Kleinen Slider-Indikator zeichnen
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
QRect barRect = sliderRect;
int yOffset = sliderRect.height()/2;
barRect.setY( rect.y() + yOffset - 3 );
barRect.setHeight( 6);
// Mini Progress Bar: der Gesamtbereich
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(0xE0E0E0));
painter->drawRoundedRect(barRect, 4, 4);
// Mini Progress Bar: der Wertebereich
barRect.setWidth( ratio * barRect.width() );
painter->setBrush(QColor(0x0078D4));
painter->drawRoundedRect(barRect, 4, 4);
painter->restore();
}
void BCValueDelegate::paintHighlightRow(QPainter* painter, const QStyleOptionViewItem& option, int row) const
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
qreal opacity =_rowOpacities.value(row);
painter->setOpacity(opacity);
// Margin von 2px
const int m = 3;
QRect itemRect = option.rect.adjusted(m,m,-m,-m);
// Border (2px solid #2196F3)
// oranger rahmen
QPen borderPen( QColor(0xFF8C00), 1);
painter->setPen(borderPen);
painter->setBrush(Qt::NoBrush);
// highlight background
//QColor highlightColor = option.palette.highlight().color();
//highlightColor.setAlphaF(0.3); // 0.0 bis 1.0 (float ist oft lesbarer)
//painter->fillRect(option.rect, highlightColor);
painter->drawRoundedRect(itemRect, 2, 2);
painter->restore();
}
void BCValueDelegate::paintPlainToggleSwitch(QPainter* painter, const QStyleOptionViewItem& option, const BCValue& bcValue) const
{
BCToggleSwitch::paintToggleIndicator(painter, option.rect, bcValue.isChecked(), 20, option.widget->palette());
}
/**
* @brief Startet die Animation für die übergebene Zeile
* @param row
*/
void BCValueDelegate::onHighlightRow(int row)
{
// Alte Animation für diese Zeile stoppen falls vorhanden
if (_rowAnimations.contains(row))
{
_rowAnimations[row]->stop();
_rowAnimations[row]->deleteLater();
}
// QVariantAnimation ist flexibler als QPropertyAnimation
auto* anim = new QVariantAnimation(this);
anim->setDuration(800);
anim->setStartValue(0.0);
anim->setEndValue(1.0);
// Custom Easing für Fade-in/out Effekt
anim->setEasingCurve(QEasingCurve::OutQuad);
connect(anim, &QVariantAnimation::valueChanged, this, [this, row](const QVariant& value)
{
qreal progress = value.toReal();
qreal opacity;
// Schnelles Fade-in (20%), langsames Fade-out (80%)
if (progress < 0.2) {
opacity = progress * 5.0; // 0->1 in 20%
}
else
{
opacity = 1.0 - ((progress - 0.2) / 0.8); // 1->0 in 80%
}
_rowOpacities[row] = opacity;
updateRow(row);
});
connect(anim, &QVariantAnimation::finished, this, [this, row, anim]()
{
_rowOpacities.remove(row);
_rowAnimations.remove(row);
updateRow(row);
anim->deleteLater();
});
_rowAnimations[row] = anim;
anim->start(QAbstractAnimation::DeleteWhenStopped);
}
/**
* @brief Stopt alle gerade laufenden Animationen
*/
void BCValueDelegate::clearAllHighlights()
{
for(auto* anim : std::as_const(_rowAnimations))
{
anim->stop();
anim->deleteLater();
}
_rowAnimations.clear();
_rowOpacities.clear();
if (_view)
_view->viewport()->update();
}
/**
* @brief Zeichnet die übegebene Zeile neu.
* @param row
*/
void BCValueDelegate::updateRow(int row)
{
if (_view && _view->model() && row >= 0)
{
QModelIndex idx = _view->model()->index(row,1);
QRect rect = _view->visualRect(idx);
if (!rect.isEmpty())
_view->viewport()->update(rect);
}
}