Analog Clock Window Example▲

Clock Window example
This example demonstrates how the transformation and scaling features of QPainter can be used to make drawing easier.
AnalogClockWindow Class Definition▲
The AnalogClockWindow class provides a clock with hour and minute hands that is automatically updated every few seconds. We make use of the RasterWindow from the Raster Window Example and reimplement the render function to draw the clock face:
class
AnalogClockWindow : public
RasterWindow
{
public
:
AnalogClockWindow();
protected
:
void
timerEvent(QTimerEvent *
) override
;
void
render(QPainter *
p) override
;
private
:
int
m_timerId;
}
;
AnalogClock Class Implementation▲
AnalogClockWindow::
AnalogClockWindow()
{
setTitle("Analog Clock"
);
resize(200
, 200
);
m_timerId =
startTimer(1000
);
}
We set a title on the window and resize to a reasonable size. Then we start a timer which we will use to redraw the clock every second.
void
AnalogClockWindow::
timerEvent(QTimerEvent *
event)
{
if
(event-&
gt;timerId() ==
m_timerId)
renderLater();
}
The timerEvent function is called every second as a result of our startTimer call. Making use of the convenience in the base class, we schedule the window to be repainted.
Checking the timer's id is not strictly needed as we only have one active timer in this instance, but it is good practice to do so.
void
AnalogClockWindow::
render(QPainter *
p)
{
static
const
QPoint hourHand[3
] =
{
QPoint(7
, 8
),
QPoint(-
7
, 8
),
QPoint(0
, -
40
)
}
;
static
const
QPoint minuteHand[3
] =
{
QPoint(7
, 8
),
QPoint(-
7
, 8
),
QPoint(0
, -
70
)
}
;
QColor hourColor(127
, 0
, 127
);
QColor minuteColor(0
, 127
, 127
, 191
);
Before we set up the painter and draw the clock, we first define two lists of QPoints and two QColors that will be used for the hour and minute hands. The minute hand's color has an alpha component of 191, meaning that it's 75% opaque.
p-&
gt;setRenderHint(QPainter::
Antialiasing);
We call QPainter::setRenderHint() with QPainter::Antialiasing to turn on antialiasing. This makes drawing of diagonal lines much smoother.
p-&
gt;translate(width() /
2
, height() /
2
);
int
side =
qMin(width(), height());
p-&