qt学习analogclock 20100919

qt demo中的analogclock例子,做了一点点的尝试修改,加了点注释。

 

analogclock.h---------------------------------------------------------------------------------------
#ifndef ANALOGCLOCK_H
#define ANALOGCLOCK_H

#include <QWidget>

class AnalogClock : public QWidget
{
Q_OBJECT

public:
AnalogClock(QWidget* parent = 0);

protected:
/*
description
*/
virtual void paintEvent(QPaintEvent* event);

virtual void testPaint(QPaintEvent* event);
};
analogclock.h---------------------------------------------------------------------------------------

analogclock.cpp---------------------------------------------------------------------------------------
#include "analogclock.h"
#include <QPainter>
#include <QTimer>
#include <QTime>
#include <QPointer>
#include <QColor>

AnalogClock::AnalogClock(QWidget* parent)
:QWidget(parent)
{
QTimer* timer(new QTimer(this));
connect(timer, SIGNAL(timeout()), this, SLOT(repaint()));
timer->start(1000);

setWindowTitle(tr("Analog Clock"));
resize(100, 100);
}

void AnalogClock::paintEvent(QPaintEvent *event)
{
this->testPaint(event);
}

void AnalogClock::testPaint(QPaintEvent *event)
{
//绘制时针、分针的指针
static const QPoint hourHand[2] =
{
QPoint(0, 0),
QPoint(0, -50)
};
static const QPoint minuteHand[2] =
{
QPoint(0, 0),
QPoint(0, -80)
};

//时针、分针的指针颜色
QColor hourColor(127, 0, 127);
QColor minuteColor(0, 127, 127, 191);

//获取边框的最小值
int side(qMin(width(), height()));

//获取当前时间
QTime time(QTime::currentTime());

//设置绘画者是自己,QPainter实例可以在任何QPaintDevice实例上绘制
QPainter painter(this);

//打开抗锯齿性能,使图像看的更加流畅
painter.setRenderHint(QPainter::Antialiasing);

painter.translate(width() / 2, height() / 2);

//通过比例放缩,保证绘制的的图像始终在widget中,且图框的左上角坐标为(-100, -100),右下角坐标为(100, 100)
painter.scale(side / 200.0, side / 200.0);

//根据color绘制为Qt::SolidLine的笔
painter.setPen(hourColor);

//save方法与restore方法要配合使用,保存当前painter实例的状态
painter.save();

//根据当前时间,将坐标旋转相应的角度,此公式为定式
painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));

painter.drawLine(hourHand[0], hourHand[1]);
painter.restore();

painter.save();

//绘制表盘上24小时时刻
for(int i(0); i != 12; ++i)
{
painter.drawLine(0, 90, 0, 100);
painter.rotate(30.0);
}
painter.restore();

painter.setPen(minuteColor);

painter.save();
painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
painter.drawLine(minuteHand[0], minuteHand[1]);
painter.restore();

painter.save();
for (int j(0); j != 60; ++j)
{
if ((j % 5) != 0)
painter.drawLine(92, 0, 96, 0);

painter.rotate(6.0);
}
painter.restore();
}
analogclock.cpp---------------------------------------------------------------------------------------

main.cpp-----------------------------------------------------------------------------------------------
#include <QApplication>
#include "analogclock.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

AnalogClock clock;
clock.show();

return a.exec();
}
main.cpp-----------------------------------------------------------------------------------------------

你可能感兴趣的:(Lock)