673e199f89eb55ef96c67fe78148c19692da9988
[electrum-nvc.git] / gui / qt / amountedit.py
1 # -*- coding: utf-8 -*-
2
3 from PyQt4.QtCore import *
4 from PyQt4.QtGui import *
5
6 from decimal import Decimal
7
8 class MyLineEdit(QLineEdit):
9
10     def setFrozen(self, b):
11         self.setReadOnly(b)
12         self.setFrame(not b)
13
14 class AmountEdit(MyLineEdit):
15
16     def __init__(self, base_unit, is_int = False, parent=None):
17         QLineEdit.__init__(self, parent)
18         self.base_unit = base_unit
19         self.textChanged.connect(self.numbify)
20         self.is_int = is_int
21         self.is_shortcut = False
22         self.help_palette = QPalette()
23
24     def numbify(self):
25         text = unicode(self.text()).strip()
26         if text == '!':
27             self.is_shortcut = True
28         pos = self.cursorPosition()
29         chars = '0123456789'
30         if not self.is_int: chars +='.'
31         s = ''.join([i for i in text if i in chars])
32         if not self.is_int:
33             if '.' in s:
34                 p = s.find('.')
35                 s = s.replace('.','')
36                 s = s[:p] + '.' + s[p:p+8]
37         self.setText(s)
38         self.setCursorPosition(pos)
39
40     def paintEvent(self, event):
41         QLineEdit.paintEvent(self, event)
42         if self.base_unit:
43             panel = QStyleOptionFrameV2()
44             self.initStyleOption(panel)
45             textRect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
46             textRect.adjust(2, 0, -10, 0)
47             painter = QPainter(self)
48             painter.setPen(self.help_palette.brush(QPalette.Disabled, QPalette.Text).color())
49             painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter, self.base_unit())
50
51
52
53 class BTCAmountEdit(AmountEdit):
54
55     def __init__(self, decimal_point, is_int = False, parent=None):
56         AmountEdit.__init__(self, self._base_unit, is_int, parent)
57         self.decimal_point = decimal_point
58
59     def _base_unit(self):
60         p = self.decimal_point()
61         assert p in [5,8]
62         return "BTC" if p == 8 else "mBTC"
63
64     def get_amount(self):
65         try:
66             x = Decimal(str(self.text()))
67         except:
68             return None
69         p = pow(10, self.decimal_point())
70         return int( p * x )
71
72     def setAmount(self, amount):
73         p = pow(10, self.decimal_point())
74         x = amount / Decimal(p)
75         self.setText(str(x))
76