Move match inside match_info in MatchHandler.
[kaya.git] / lib / constrained_text_item.rb
blobecd566528eef59704d16c1ac2ea16bf05ed5d57f
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 class ConstrainedTextItem < Qt::GraphicsItem
9   attr_reader :text
11   def initialize(text, parent, constraint = Qt::RectF.new, opts = {})
12     super(parent)
13     @text = text.to_s
14     @parent = parent
15     @constraint = constraint
16     
17     @font = opts[:font] || Qt::Font.new
18     @fm = Qt::FontMetrics.new(@font)
19     @color = opts[:color] || Qt::Color.new(Qt::black)
20     
21     update_metrics
22   end
23   
24   def paint(p, opts, widget)
25     p.pen = @color
26     p.font = @font
27     p.saving do
28       p.translate(@constraint.center)
29       p.scale(@factor, @factor)
30       p.translate(-@brect_max.center)
31       p.draw_text((@brect_max.width - @brect.width) / 2, 0, @text)
32     end
33   end
34   
35   def boundingRect
36     @constraint
37   end
39   def text=(value)
40     @text = value.to_s
41     update_metrics
42     update @constraint
43   end
44   
45   def constraint=(value)
46     @constraint = value
47     update_metrics
48     update @constraint
49   end
50   
51   def color=(value)
52     @color = value
53     update @constraint
54   end
55   
56   def update_metrics
57     if @text.empty?
58       @brect = @constraint
59       @brect_max = @constraint
60       @factor = 1.0
61     else
62       @brect = @fm.bounding_rect(@text)
63       @brect_max = @fm.bounding_rect('H' * @text.size)
64       @factor = [
65         @constraint.width / @brect_max.width,
66         @constraint.height / @brect_max.height].min
67     end
68   end
69   
70   alias :name :text  
71 end