The clock is now skinnable.
[kaya.git] / lib / constrained_text_item.rb
blob273fe5ef5d649c4b0ef2dfdb08354903fe4ecf5b
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 = value
40     update_metrics
41     update @constraint
42   end
43   
44   def update_metrics
45     if @text.empty?
46       @brect = @constraint
47       @brect_max = @constraint
48       @factor = 1.0
49     else
50       @brect = @fm.bounding_rect(@text)
51       @brect_max = @fm.bounding_rect('H' * @text.size)
52       @factor = [
53         @constraint.width / @brect_max.width,
54         @constraint.height / @brect_max.height].min
55     end
56   end
57   
58   alias :name :text  
59 end