fix
[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 AmountEdit(QLineEdit):
9
10     def __init__(self, decimal_point, is_int = False, parent=None):
11         QLineEdit.__init__(self, parent)
12         self.decimal_point = decimal_point
13         self.textChanged.connect(self.numbify)
14         self.is_int = is_int
15         self.is_shortcut = False
16
17     def base_unit(self):
18         p = self.decimal_point()
19         assert p in [5,8]
20         return "BTC" if p == 8 else "mBTC"
21
22     def get_amount(self):
23         x = unicode( self.text() )
24         if x in['.', '']: 
25             return None
26         p = pow(10, self.decimal_point())
27         return int( p * Decimal(x) )
28
29     def setAmount(self, amount):
30         p = pow(10, self.decimal_point())
31         x = amount / Decimal(p)
32         self.setText(str(x))
33
34     def paintEvent(self, event):
35         QLineEdit.paintEvent(self, event)
36         if self.decimal_point:
37              panel = QStyleOptionFrameV2()
38              self.initStyleOption(panel)
39              textRect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
40              textRect.adjust(2, 0, -10, 0)
41              painter = QPainter(self)
42              painter.setPen(self.palette().brush(QPalette.Disabled, QPalette.Text).color())
43              painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter, self.base_unit())
44
45
46     def numbify(self):
47         text = unicode(self.text()).strip()
48         if text == '!':
49             self.is_shortcut = True
50         pos = self.cursorPosition()
51         chars = '0123456789'
52         if not self.is_int: chars +='.'
53         s = ''.join([i for i in text if i in chars])
54         if not self.is_int:
55             if '.' in s:
56                 p = s.find('.')
57                 s = s.replace('.','')
58                 s = s[:p] + '.' + s[p:p+8]
59         self.setText(s)
60         self.setCursorPosition(pos)
61
62