Add rounded rect around time.
[kaya/ydirson.git] / lib / constrained_text_item.rb
blobb66062151ba5b3e801654e71b7c85cbc5f14523d
1 class ConstrainedTextItem < Qt::GraphicsItem
2   attr_reader :text
4   def initialize(text, parent, constraint = Qt::RectF.new, opts = {})
5     super(parent)
6     @text = text.to_s
7     @parent = parent
8     @constraint = constraint
9     
10     @font = opts[:font] || Qt::Font.new
11     @fm = Qt::FontMetrics.new(@font)
12     @color = opts[:color] || Qt::Color.new(Qt::black)
13     
14     update_metrics
15   end
16   
17   def paint(p, opts, widget)
18     p.pen = @color
19     p.font = @font
20     p.saving do
21       p.translate(@constraint.center)
22       p.scale(@factor, @factor)
23       p.translate(-@brect_max.center)
24       p.draw_text((@brect_max.width - @brect.width) / 2, 0, @text)
25     end
26   end
27   
28   def boundingRect
29     @constraint
30   end
32   def text=(value)
33     @text = value.to_s
34     update_metrics
35     update @constraint
36   end
37   
38   def constraint=(value)
39     @constraint = Qt::RectF.new(value)
40     update_metrics
41     update @constraint
42   end
43   
44   def update_metrics
45     @brect = @fm.bounding_rect(@text)
46     @brect_max = @fm.bounding_rect('H' * @text.size)
47     @factor = [
48       @constraint.width / @brect_max.width,
49       @constraint.height / @brect_max.height].min
50   end
51   
52   alias :name :text  
53 end