1、作业需求
使用QT制作一个简单的时钟。
2、实现过程
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
timer = new QTimer(this);
timer->start(1000);
connect(timer, &QTimer::timeout, [&](){
count++;
update();
});
//获取时间
QTime time = QTime::currentTime();
//将时间转换成字符串
QString t = time.toString("HH:mm:ss");
//将时间切片,单独将时、分、秒拿出来
QStringList timeList = t.split(':'); //通过split()函数将字符串分割成3个片段
//将字符串转换为无符号整数,(quint8:8位数的无符号整形)
hour = timeList[0].toUInt(); //时
minute = timeList[1].toUInt(); //分
second = timeList[2].toUInt(); //秒
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter pa(this); //画家类
QBrush br(QColor("pink")); //刷子类(粉红色)
QPen pe; //画笔类
//pa.setPen(Qt::black);
//pa.setFont(QFont("黑体", 100));
pa.setBrush(br);
pa.translate(this->width()/2, this->height()/2);
//pa.setPen(QColor("blue"));
pe.setWidth(3);
pe.setColor("blue");
pa.setPen(pe);
pa.drawEllipse(QPoint(0, 0), 200, 200);
for(int i=0; i<12; i++) { //粗刻度线
pe.setWidth(6);
pe.setColor("black");
pa.setPen(pe);
pa.drawLine(QPoint(0, 180), QPoint(0, 195));
pa.rotate(30);
}
for(int i=0; i<60; i++) { //细刻度线
pe.setWidth(3);
pe.setColor("black");
pa.setPen(pe);
pa.drawLine(QPoint(0,199), QPoint(0,190));
pa.rotate(6);
}
for(int i=0; i<12; i++) { //表盘数字
pe.setColor("black");
pa.setFont(QFont("宋体", 10));
if(0==i) {
pa.drawText(QPoint(-10,-160),QString::number(12));
}else if(10==i || 11==i){
pa.drawText(QPoint(-9,-160),QString::number(i));
}else {
pa.drawText(QPoint(-5,-160),QString::number(i));
}
pa.rotate(30);
}
//制作时针
pe.setWidth(10);
pe.setColor("green");
pa.setPen(pe);
pa.rotate(30*hour+30*minute/60+6*second/60/12+6*count/60/12);
pa.drawLine(QPoint(0,-80), QPoint(0,5));
//制作分针
QPainter pa1(this);
pa1.translate(this->width()/2,this->height()/2);
pe.setWidth(6);
pe.setColor("blue");
pa1.setPen(pe);
pa1.rotate(6*minute+6*second/60+6*count/60);
pa1.drawLine(QPoint(0,-100), QPoint(0,8));
//制作秒针
QPainter pa2(this);
pa2.translate(this->width()/2,this->height()/2);
pe.setWidth(4);
pe.setColor("red");
pa2.setPen(pe);
pa2.rotate(6*second+6*count);
pa2.drawLine(QPoint(0,-150), QPoint(0,8));
}
3、效果截图