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