时间是伟大的导师,时间就是金钱,一寸光阴一寸金,寸金难买寸光阴,莫等闲,白了少年头,空悲切。珍惜时间啊小姐姐们,好了不扯犊子了,用qt做一个带时分秒的指针时钟,先来看看效果吧
效果视频
https://www.zhihu.com/zvideo/1254392077057339392
软件结构
![1216dc9cca92ad9e2f44ca5161cead6a.png](https://img-blog.csdnimg.cn/img_convert/1216dc9cca92ad9e2f44ca5161cead6a.png)
现在开始讲一下源码吧
引入头文件
#include <QGuiApplication>
看一下解释
![12574eaab9516074724720c7adbb11af.png](https://img-blog.csdnimg.cn/img_convert/12574eaab9516074724720c7adbb11af.png)
有图形界面,只使用QML实现,使用QGuiApplication
引入头文件
#include <QQmlApplicationEngine>
QQmlApplicationEngine提供了从一个QML文件里面加载应用程序的方式。
这类联合了QQmlEngine和QmlComponent去加载单独的QML文件。他还向QML提供了应用程序的功能,这个应用程序的功能能够让C++与QML混合编程,使用C++控制业务逻辑,用QML做界面。
在main函数中我们就可以这样使用了
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
improt语句
main.qml 文件第一行代码:import QtQuick 2.9 。这行代码引入了 QtQuick 模块, import 语句的作用与 C++ 中的 #include 类似,也与 Java 中的 import 效果一样.
设置时分秒指针颜色
property string hourColor: "#B23AEE"
property string minuteColor: "#43CD80"
property string secondColor: "#B8860B"
在QML中使用Timer元素来表示一个定时器
interval
: 500; running: true; repeat: true
onTriggered: {
var date = new Date();
hour = date.getHours();
minute = date.getMinutes();
second = date.getSeconds();
canvas.requestPaint();
}
interval属性:设置时间间隔,单位ms
repeat属性:是否重复触发。如果是false则只触发一次并自动将running属性设置为false.默认值为true。
running属性:true开启定时器。默认true。
当定时器触发时会执行onTriggered()信号处理函数,在这里可以定义一些操作;
绘制时分秒
//绘制刻度
drawScaleValue(ctx);
//绘制时针
drawClockHand(ctx, 1);
//绘制分针
drawClockHand(ctx, 2);
//绘制秒针
drawClockHand(ctx, 3);
先来看看怎么绘制刻度的,圆圈360°,每个小时刻度之间的夹角30°,这个无需解释吧,先看看getContext函数
getContext由get(获取)+context(上下文)构成。由此可以猜测此方法的功能是获取绘图上下文环境,通俗的讲,就是为canvas绘图提供绘图的一些必要条件。
var ctx = getContext("2d");
var centerX = centerPoint().x;
var centerY = centerPoint().y;
var isHour = ((i % 30) == 0);
var radius = centerX < centerY ? (centerX - margin) : (centerY - margin);
ctx.strokeStyle = isHour ? canvas.hourColor : canvas.minuteColor;
翻转,绘制,移动到圆中心
ctx.translate(centerX, centerY);
ctx.rotate(deg2Rad(i));
ctx.beginPath();
ctx.moveTo(radius, 0);
再看看怎么绘制时分秒,我们知道时分秒指针长度是不一样的,相同时间点走的角度也不一样,看代码
ctx.globalCompositeOperation = "source-over";
在先绘制的图形上显示后绘制的图形。相交部分由后绘制的图形填充(颜色,渐变,纹理)覆盖。
先了解deg2Rad函数,把角度值转换为弧度值。fillStyle函数,fillStyle与Qt C++中的QBrush类似,保存用于填充图元的画刷,它可以是一个颜色值,也可以是CanvasGradient或CanvasPattern对象。
绘制时钟
ctx.fillStyle = hourColor;
angle = deg2Rad(30.0 * (timer.hour + timer.minute / 60.0));
绘制分钟
ctx.fillStyle = minuteColor;
angle = deg2Rad(6.0 * timer.minute);
handPoint3.x = 0; handPoint3.y = -130;
绘制秒钟
ctx.fillStyle = secondColor;
angle = deg2Rad(6.0 * timer.second);
handPoint3.x = 0; handPoint3.y = -180;
最后要了解一下QT 基本图形绘制的一些函数,大家可以在qt creator Help里面查找看看具体的定义以及用法。
总结
这里使用的是qml方式实现,想要做时钟有很多方法,也有很多必需功能,例如设置时间,切换北京时间或者伦敦时间,或者设置闹钟等等功能,主要起到抛砖引玉的功能,希望大家一起多交流,共进步。