#include "itemnumberdelegate.h"

#include <QDoubleSpinBox>

ItemNumberDelegate::ItemNumberDelegate(double min, double max, double step,
                                       int precision, QObject *parent) :
    QItemDelegate(parent),
    m_min(min),
    m_max(max),
    m_step(step),
    m_precision(precision)
{
}

QWidget *ItemNumberDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
    editor->setMinimum(m_min);
    editor->setMaximum(m_max);
    editor->setDecimals(m_precision);
    editor->setSingleStep(m_step);
    editor->installEventFilter(const_cast<ItemNumberDelegate *>(this));
    editor->setButtonSymbols(QAbstractSpinBox::NoButtons);
    //editor->setFrame(false);
    editor->setAlignment(Qt::AlignRight);
    return editor;
}

void ItemNumberDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    double value = index.model()->data(index, Qt::EditRole).toDouble();
    static_cast<QDoubleSpinBox*>(editor)->setValue(value);
}

void ItemNumberDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex& index) const
{
    QDoubleSpinBox *dsb = static_cast<QDoubleSpinBox*>(editor);
    dsb->interpretText();
    double value = dsb->value();
    model->setData(index, value, Qt::EditRole);
}

void ItemNumberDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                         const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}
