LabelItem.py 4.91 KB
Newer Older
1
2
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
3
import pyqtgraph as pg
4
from .GraphicsWidget import GraphicsWidget
5
6
7
8
9
10
11
12
13


__all__ = ['LabelItem']

class LabelItem(GraphicsWidget):
    """
    GraphicsWidget displaying text.
    Used mainly as axis labels, titles, etc.
    
14
    Note: To display text inside a scaled view (ViewBox, PlotWidget, etc) use TextItem
15
16
17
    """
    
    
18
    def __init__(self, text=' ', parent=None, angle=0, **args):
19
20
        GraphicsWidget.__init__(self, parent)
        self.item = QtGui.QGraphicsTextItem(self)
21
        self.opts = {
22
            'color': None,
23
24
25
            'justify': 'center'
        }
        self.opts.update(args)
26
        self._sizeHint = {}
27
        self.setText(text)
28
        self.setAngle(angle)
29
30
31
32
33
34
35
36
            
    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:
37
38
39
40
41
42
43
44
45

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