setFrozen generic method
[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, decimal_point, is_int = False, parent=None):
17         QLineEdit.__init__(self, parent)
18         self.decimal_point = decimal_point
19         self.textChanged.connect(self.numbify)
20         self.is_int = is_int
21         self.is_shortcut = False
22
23     def base_unit(self):
24         p = self.decimal_point()
25         assert p in [5,8]
26         return "BTC" if p == 8 else "mBTC"
27
28     def get_amount(self):
29         x = unicode( self.text() )
30         if x in['.', '']: 
31             return None
32         p = pow(10, self.decimal_point())
33         return int( p * Decimal(x) )
34
35     def setAmount(self, amount):
36         p = pow(10, self.decimal_point())
37         x = amount / Decimal(p)
38         self.setText(str(x))
39
40     def paintEvent(self, event):
41         QLineEdit.paintEvent(self, event)
42         if self.decimal_point:
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.palette().brush(QPalette.Disabled, QPalette.Text).color())
49              painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter, self.base_unit())
50
51
52     def numbify(self):
53         text = unicode(self.text()).strip()
54         if text == '!':
55             self.is_shortcut = True
56         pos = self.cursorPosition()
57         chars = '0123456789'
58         if not self.is_int: chars +='.'
59         s = ''.join([i for i in text if i in chars])
60         if not self.is_int:
61             if '.' in s:
62                 p = s.find('.')
63                 s = s.replace('.','')
64                 s = s[:p] + '.' + s[p:p+8]
65         self.setText(s)
66         self.setCursorPosition(pos)
67
68