separate AmountEdit and BTCAmountEdit classes, for exchange rate plugin
[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
23     def numbify(self):
24         text = unicode(self.text()).strip()
25         if text == '!':
26             self.is_shortcut = True
27         pos = self.cursorPosition()
28         chars = '0123456789'
29         if not self.is_int: chars +='.'
30         s = ''.join([i for i in text if i in chars])
31         if not self.is_int:
32             if '.' in s:
33                 p = s.find('.')
34                 s = s.replace('.','')
35                 s = s[:p] + '.' + s[p:p+8]
36         self.setText(s)
37         self.setCursorPosition(pos)
38
39     def paintEvent(self, event):
40         QLineEdit.paintEvent(self, event)
41         if self.base_unit:
42              panel = QStyleOptionFrameV2()
43              self.initStyleOption(panel)
44              textRect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
45              textRect.adjust(2, 0, -10, 0)
46              painter = QPainter(self)
47              painter.setPen(self.palette().brush(QPalette.Disabled, QPalette.Text).color())
48              painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter, self.base_unit())
49
50
51
52 class BTCAmountEdit(AmountEdit):
53
54     def __init__(self, decimal_point, is_int = False, parent=None):
55         QLineEdit.__init__(self, parent)
56         self.decimal_point = decimal_point
57         self.textChanged.connect(self.numbify)
58         self.is_int = is_int
59         self.is_shortcut = False
60
61     def base_unit(self):
62         p = self.decimal_point()
63         assert p in [5,8]
64         return "BTC" if p == 8 else "mBTC"
65
66     def get_amount(self):
67         x = unicode( self.text() )
68         if x in['.', '']: 
69             return None
70         p = pow(10, self.decimal_point())
71         return int( p * Decimal(x) )
72
73     def setAmount(self, amount):
74         p = pow(10, self.decimal_point())
75         x = amount / Decimal(p)
76         self.setText(str(x))
77