本周作业是利用Qt中所学相关QTimer和QPainter的知识,设计一个外表美观的动态时钟。
最终我设计的效果图如下:
(1)构造一个定时器QTimer,连接超时信号timeout()到槽函数update()
(2)当调用update()的时候,系统会通知当前界面进行重绘。
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
setWindowTitle(tr("My Clock"));
resize(500,500);
注意:使用QTimer定时刷新,设置超时时间为1s.
(1)文本区域通过textRectF()计算。
(2)实现一个用于获取文本区域的接口
QRectF Widget::textRectF(double radius, int pointSize, double angle)
{
QRectF rectF;
rectF.setX(radius*cos(angle*M_PI/180.0) - pointSize*2);
rectF.setY(radius*sin(angle*M_PI/180.0) - pointSize/2.0);
rectF.setWidth(pointSize*4);
rectF.setHeight(pointSize);
return rectF;
}
重写paintEvent(),用于绘制时钟
void Widget::paintEvent(QPaintEvent * event)
(1)插入自己喜欢的背景图片
此处还是要用QPixmap和QRect规定背景图片显示的大小。
QPainter painter1(this);
QPixmap map(":/res/1.jpg");
QRect q(0,0,500,500);
QRect q2(0,0,width(),height());
painter1.drawPixmap(q2,map,q);
注意:这里一定要先插入背景图片再绘制时钟,如果顺序反了,图片会覆盖所绘时钟。
(2)时针、分针、秒针位置(多边形)
static const QPoint hourHand[3]=
{
QPoint(7,8),
QPoint(-7,8),
QPoint(0,30)
};
static const QPoint minuteHand[3]=
{
QPoint(7,8),
QPoint(-7,8),
QPoint(0,-65)
};
static const QPoint secondHand[3]=
{
QPoint(7,8),
QPoint(-7,8),
QPoint(0,-80)
};
(3)时针,分针,秒针颜色
QColor hourColor(219,112,147);
QColor minuteColor(30,144,255);
QColor secondColor(100,149,237);
注意:这里的颜色可以根据自己喜欢和与背景图片颜色适配度自己选择,详见
https://www.cnblogs.com/xpvincent/archive/2012/12/17/2821665.html
(4)平移坐标系原点至中心点并缩放
int side =qMin(width(),height());
QTime time = QTime::currentTime();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 200.0, side / 200.0);
(5)绘制时针
(每圈360°=12h,即:旋转角度=小时数*30°)
painter.setPen(Qt::NoPen);
painter.setBrush(hourColor);
painter.save();
painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
painter.drawConvexPolygon(hourHand, 3);
painter.restore();
painter.setPen(hourColor);
(6)绘制小时线
(360°/12=30°)
for (int i = 0; i < 12; ++i) {
painter.drawLine(88, 0, 96, 0);
painter.rotate(30.0);
}
int radius = 100;
QFont font = painter.font();
font.setBold(true);
painter.setFont(font);
int pointSize = font.pointSize();
(7)绘制小时文本(即时钟上1-12)
int nHour = 0;
for (int i = 0; i < 12; ++i)
{
nHour = i + 3;
if (nHour > 12)
nHour -= 12;
painter.drawText(textRectF(radius*0.8, pointSize, i * 30), Qt::AlignCenter, QString::number(nHour));
}
(8)绘制分针秒针和分钟线秒钟线,原理同上
painter.setPen(Qt::NoPen);
painter.setBrush(minuteColor);
painter.save();
painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
painter.drawConvexPolygon(minuteHand, 3);
painter.restore();
painter.setPen(minuteColor);
for (int j = 0; j < 60; ++j) {
if ((j % 5) != 0)
painter.drawLine(92, 0, 96, 0);
painter.rotate(6.0);
}
painter.setPen(Qt::NoPen);
painter.setBrush(secondColor);
painter.save();
painter.rotate(6.0 * time.second());
painter.drawConvexPolygon(secondHand, 3);
painter.restore();
参考:https://yq.aliyun.com/articles/119927
源码:https://download.csdn.net/download/Mini_YY/12473961