Add constrained text item.
[kaya.git] / lib / constrained_text_item.rb
blob694fc17eca1d386c8b57f18741dd5022f4f02ead
1 class ConstrainedTextItem < Qt::GraphicsItem
2   def initialize(text, parent, constraint, opts = {})
3     super(parent)
4     @text = text
5     @parent = parent
6     @constraint = constraint
7     
8     @font = opts[:font] || Qt::Font.new
9     @color = opts[:color] || Qt::Color.new(Qt::black)
10     
11     @brect = Qt::FontMetrics.new(@font).bounding_rect(@text)
12     @factor = [
13       0.9 * @constraint.width / @brect.width,
14       @constraint.height / @brect.height].min
15   end
16   
17   def paint(p, opts, widget)
18     p.pen = @color
19     p.font = @font
20     p.draw_rect @constraint
21     p.saving do
22       p.translate(@constraint.center)
23       p.scale(@factor, @factor)
24       p.translate(-@brect.center)
25       p.draw_text(0, 0, @text)
26     end
27   end
28   
29   def boundingRect
30     @constraint
31   end
32   
33   def name
34     @text
35   end
36 end