introduce bitcoin amount field with split amount/decimals, to protect against mistake...
[novacoin.git] / src / qt / bitcoinamountfield.cpp
1 #include "bitcoinamountfield.h"
2
3 #include <QLabel>
4 #include <QLineEdit>
5 #include <QRegExpValidator>
6 #include <QHBoxLayout>
7 #include <QKeyEvent>
8
9 BitcoinAmountField::BitcoinAmountField(QWidget *parent):
10         QWidget(parent), amount(0), decimals(0)
11 {
12     amount = new QLineEdit(this);
13     amount->setValidator(new QRegExpValidator(QRegExp("[0-9]+"), this));
14     amount->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
15     amount->installEventFilter(this);
16     amount->setMaximumWidth(80);
17     decimals = new QLineEdit(this);
18     decimals->setValidator(new QRegExpValidator(QRegExp("[0-9]+"), this));
19     decimals->setMaxLength(8);
20     decimals->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
21     decimals->setMaximumWidth(75);
22
23     QHBoxLayout *layout = new QHBoxLayout(this);
24     layout->setSpacing(0);
25     layout->addWidget(amount);
26     layout->addWidget(new QLabel(QString(".")));
27     layout->addWidget(decimals);
28     layout->addStretch(1);
29
30     setFocusPolicy(Qt::TabFocus);
31     setLayout(layout);
32     setFocusProxy(amount);
33
34     // If one if the widgets changes, the combined content changes as well
35     connect(amount, SIGNAL(textChanged(QString)), this, SIGNAL(textChanged()));
36     connect(decimals, SIGNAL(textChanged(QString)), this, SIGNAL(textChanged()));
37 }
38
39 void BitcoinAmountField::setText(const QString &text)
40 {
41     const QStringList parts = text.split(QString("."));
42     if(parts.size() == 2)
43     {
44         amount->setText(parts[0]);
45         decimals->setText(parts[1]);
46     }
47 }
48
49 QString BitcoinAmountField::text() const
50 {
51     return amount->text() + QString(".") + decimals->text();
52 }
53
54 // Intercept '.' and ',' keys, if pressed focus a specified widget
55 bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
56 {
57     Q_UNUSED(object);
58     if(event->type() == QEvent::KeyPress)
59     {
60         QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
61         if(keyEvent->key() == Qt::Key_Period || keyEvent->key() == Qt::Key_Comma)
62         {
63             decimals->setFocus();
64         }
65     }
66     return false;
67 }