summaryrefslogtreecommitdiffstats
path: root/qtruby/rubylib/examples/qt-examples/aclock/aclock.rb
blob: a2cdc3784785caf37ee575dfc9be35473bfc835f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env ruby -w

require 'Qt'

# an analog clock widget using an internal QTimer
class AnalogClock < Qt::Widget
	slots 'setTime(const QTime&)', 'drawClock(QPainter*)', 'timeout()'

	def initialize(*k)
		super(*k)

		@time = Qt::Time::currentTime
		@internalTimer = Qt::Timer.new(self)
		connect(@internalTimer, SIGNAL('timeout()'), self, SLOT('timeout()'))
		@internalTimer.start(5000)
	end

	def mousePressEvent(e)
		if isTopLevel
			topLeft = geometry.topLeft - frameGeometry.topLeft
			@clickPos = e.pos + topLeft
		end
	end

	def mouseMoveEvent(e)
		if isTopLevel
			move(e.globalPos - @clickPos) unless @clickPos.nil?
		end
	end

	def setTime(t)
		# erm. huh?
		timeout()
	end

	# The QTimer::timeout() signal is received by this slot.
	def timeout
		new_time = Qt::Time::currentTime
		@time = @time.addSecs 5
		unless new_time.minute == @time.minute
			if autoMask
				updateMask
			else
				update
			end
		end
	end

	def paintEvent(blah)
		unless autoMask
			paint = Qt::Painter.new(self)
			paint.setBrush(colorGroup.foreground)
			drawClock(paint)
			paint.end
		end
	end

	# If clock is transparent, we use updateMask() instead of paintEvent()
	def updateMask
		bm = Qt::Bitmap.new(size)
		bm.fill(color0)			# transparent

		paint = Qt::Painter.new
		paint.begin(bm, self)
		paint.setBrush(color1)		# use non-transparent color
		paint.setPen(color1)

		drawClock(paint)

		paint.end
		setMask(bm)
	end

	# The clock is painted using a 1000x1000 square coordinate system, in
	# the centered square, as big as possible.  The painter's pen and
	# brush colors are used.
	def drawClock(paint)
		paint.save

		paint.setWindow(-500,-500, 1000,1000)

		v = paint.viewport
		d = [v.width, v.height].min
		vpx = (v.left + (v.width-d)) / 2
		vpy = (v.top  - (v.height-d)) / 2
		paint.setViewport(vpx, vpy, d, d) 

		paint.save
		paint.rotate(30*(@time.hour%12-3) + @time.minute/2)
		pts = Qt::PointArray.new(4, [-20,0, 0,-20, 300,0, 0,20])
		paint.drawConvexPolygon(pts)
		paint.restore

		paint.save
		paint.rotate((@time.minute-15)*6)
		pts = Qt::PointArray.new(4, [-10,0, 0,-10, 400,0, 0,10])
		paint.drawConvexPolygon(pts)
		paint.restore;

		12.times {
			paint.drawLine(440,0, 460,0)
			paint.rotate(30)
		}

		paint.restore
	end

	def setAutoMask(background)
		setBackgroundMode(background ? PaletteForeground : PaletteBackground)
		Qt::Widget::setAutoMask(background)
	end

end