Если кому интересно - написал делегат по совету
alFoX:
currency_item_editor.h:
C++ (Qt)
#include <QItemDelegate>
class CurrencyItemEditor : public QItemDelegate
{
Q_OBJECT
public:
CurrencyItemEditor(QObject *parent);
~CurrencyItemEditor();
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *parent, const QModelIndex &index) const;
void setModelData(QWidget *parent, QAbstractItemModel *model, const QModelIndex &index) const;
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex & index ) const;
private:
};
currency_item_editor.cpp:
C++ (Qt)
#include "currency_item_editor.h"
#include "limits.h"
#include "math.h"
#include <QApplication>
#include <QtCore>
#include <QDoubleSpinBox>
#include <QPainter>
#include <QStyle>
CurrencyItemEditor::CurrencyItemEditor(QObject *parent)
: QItemDelegate(parent)
{
}
CurrencyItemEditor::~CurrencyItemEditor()
{
}
QWidget *CurrencyItemEditor::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const
{
QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
editor->setMaximum(floor(static_cast<double>(INT_MAX) / 100 + 0.5));
editor->setMinimum(floor(static_cast<double>(INT_MIN) / 100 + 0.5));
editor->setAlignment(Qt::AlignRight);
return editor;
}
void CurrencyItemEditor::setEditorData(QWidget *parent, const QModelIndex &index) const
{
double value = index.model()->data(index).toDouble() / 100;
QDoubleSpinBox *editor = static_cast<QDoubleSpinBox*>(parent);
editor->setValue(value);
}
void CurrencyItemEditor::setModelData(QWidget *parent, QAbstractItemModel *model, const QModelIndex &index) const
{
QDoubleSpinBox *editor = static_cast<QDoubleSpinBox*>(parent);
editor->interpretText();
int value = static_cast<int>(floor(editor->value() * 100 + 0.5));
model->setData(index, value);
}
void CurrencyItemEditor::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex & index ) const
{
if (option.state & QStyle::State_Selected) {
painter->fillRect(option.rect, option.palette.highlight());
painter->setPen(option.palette.highlightedText().color());
} else {
painter->setPen(option.palette.text().color());
}
double value = index.model()->data(index).toDouble() / 100;
painter->drawText(option.rect, QString("%L1\t").arg(value, 0, 'f', 2), QTextOption(Qt::AlignRight | Qt::AlignVCenter));
if (option.state & QStyle::State_HasFocus) {
QStyleOptionFocusRect optionFocusRect;
optionFocusRect.QStyleOption::operator = (option);
optionFocusRect.rect = option.rect;
optionFocusRect.state |= QStyle::State_KeyboardFocusChange;
QPalette::ColorGroup colorgroup = (option.state & QStyle::State_Enabled)
? QPalette::Normal
: QPalette::Disabled;
option.palette.color(colorgroup, (option.state & QStyle::State_Selected)
? QPalette::Highlight
: QPalette::Background );
QApplication::style()->drawPrimitive(QStyle::PE_FrameFocusRect, &optionFocusRect, painter);
}
}