LabelItem.py 5.03 KB
Newer Older
1
2
from ..Qt import QtGui, QtCore
from .. import functions as fn
3
from .GraphicsWidget import GraphicsWidget
4
from .GraphicsWidgetAnchor import GraphicsWidgetAnchor
5
from .. import getConfigOption
6
7
8
9


__all__ = ['LabelItem']

10
class LabelItem(GraphicsWidget, GraphicsWidgetAnchor):
11
12
13
14
    """
    GraphicsWidget displaying text.
    Used mainly as axis labels, titles, etc.
    
15
    Note: To display text inside a scaled view (ViewBox, PlotWidget, etc) use TextItem
16
17
18
    """
    
    
19
    def __init__(self, text=' ', parent=None, angle=0, **args):
20
        GraphicsWidget.__init__(self, parent)
21
        GraphicsWidgetAnchor.__init__(self)
22
        self.item = QtGui.QGraphicsTextItem(self)
23
        self.opts = {
24
            'color': None,
25
26
27
            'justify': 'center'
        }
        self.opts.update(args)
28
        self._sizeHint = {}
29
        self.setText(text)
30
        self.setAngle(angle)
31
32
33
34
35
36
37
38
            
    def setAttr(self, attr, value):
        """Set default text properties. See setText() for accepted parameters."""
        self.opts[attr] = value
        
    def setText(self, text, **args):
        """Set the text and text properties in the label. Accepts optional arguments for auto-generating
        a CSS style string:
39
40
41
42
43
44
45
46
47

        ==================== ==============================
        **Style Arguments:**
        color                (str) example: 'CCFF00'
        size                 (str) example: '8pt'
        bold                 (bool)
        italic               (bool)
        ==================== ==============================
        """
48
        self.text = text
49
        opts = self.opts
50
51
52
53
        for k in args:
            opts[k] = args[k]
        
        optlist = []
54
55
56
        
        color = self.opts['color']
        if color is None:
57
            color = getConfigOption('foreground')
58
59
        color = fn.mkColor(color)
        optlist.append('color: #' + fn.colorStr(color)[:6])
60
61
62
63
64
65
66
67
68
69
        if 'size' in opts:
            optlist.append('font-size: ' + opts['size'])
        if 'bold' in opts and opts['bold'] in [True, False]:
            optlist.append('font-weight: ' + {True:'bold', False:'normal'}[opts['bold']])
        if 'italic' in opts and opts['italic'] in [True, False]:
            optlist.append('font-style: ' + {True:'italic', False:'normal'}[opts['italic']])
        full = "<span style='%s'>%s</span>" % ('; '.join(optlist), text)
        #print full
        self.item.setHtml(full)
        self.updateMin()
70
        self.resizeEvent(None)
71
        self.updateGeometry()
72
73
        
    def resizeEvent(self, ev):
74
75
76
77
        #c1 = self.boundingRect().center()
        #c2 = self.item.mapToParent(self.item.boundingRect().center()) # + self.item.pos()
        #dif = c1 - c2
        #self.item.moveBy(dif.x(), dif.y())
78
        #print c1, c2, dif, self.item.pos()
79
80
81
82
83
        self.item.setPos(0,0)
        bounds = self.itemRect()
        left = self.mapFromItem(self.item, QtCore.QPointF(0,0)) - self.mapFromItem(self.item, QtCore.QPointF(1,0))
        rect = self.rect()
        
84
        if self.opts['justify'] == 'left':
85
86
87
88
89
90
91
            if left.x() != 0:
                bounds.moveLeft(rect.left())
            if left.y() < 0:
                bounds.moveTop(rect.top())
            elif left.y() > 0:
                bounds.moveBottom(rect.bottom())
                
92
        elif self.opts['justify'] == 'center':
93
94
95
            bounds.moveCenter(rect.center())
            #bounds = self.itemRect()
            #self.item.setPos(self.width()/2. - bounds.width()/2., 0)
96
        elif self.opts['justify'] == 'right':
97
98
99
100
101
102
103
104
105
106
107
            if left.x() != 0:
                bounds.moveRight(rect.right())
            if left.y() < 0:
                bounds.moveBottom(rect.bottom())
            elif left.y() > 0:
                bounds.moveTop(rect.top())
            #bounds = self.itemRect()
            #self.item.setPos(self.width() - bounds.width(), 0)
            
        self.item.setPos(bounds.topLeft() - self.itemRect().topLeft())
        self.updateMin()
108
109
110
111
112
113
114
        
    def setAngle(self, angle):
        self.angle = angle
        self.item.resetTransform()
        self.item.rotate(angle)
        self.updateMin()
        
115
        
116
    def updateMin(self):
117
        bounds = self.itemRect()
118
119
120
        self.setMinimumWidth(bounds.width())
        self.setMinimumHeight(bounds.height())
        
121
        self._sizeHint = {
122
123
124
125
126
            QtCore.Qt.MinimumSize: (bounds.width(), bounds.height()),
            QtCore.Qt.PreferredSize: (bounds.width(), bounds.height()),
            QtCore.Qt.MaximumSize: (-1, -1),  #bounds.width()*2, bounds.height()*2),
            QtCore.Qt.MinimumDescent: (0, 0)  ##?? what is this?
        }
127
        self.updateGeometry()
128
        
129
    def sizeHint(self, hint, constraint):
130
        if hint not in self._sizeHint:
131
            return QtCore.QSizeF(0, 0)
132
133
134
135
        return QtCore.QSizeF(*self._sizeHint[hint])
        
    def itemRect(self):
        return self.item.mapRectToParent(self.item.boundingRect())
136
        
137
138
139
    #def paint(self, p, *args):
        #p.setPen(fn.mkPen('r'))
        #p.drawRect(self.rect())
140
141
        #p.setPen(fn.mkPen('g'))
        #p.drawRect(self.itemRect())
142