一、绘制时钟
widget.h:
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QRectF>
#include <QTimer>
#include <QTime>
#include <QTimerEvent>
#include <QLabel>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void paintEvent(QPaintEvent *event) override;
// void timerEvent(QTimerEvent *e) override;
public slots:
void timer_slot();
private:
Ui::Widget *ui;
// int timer_id; //定义一个定时器id
QTimer * timer;
int hour;
int minute;
int second;
QLabel *label;
};
#endif // WIDGET_H
widget.cpp:
cpp
#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,this,&Widget::timer_slot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
//QRectF rectangle(this->width()/2-200,this->height()/2-200,400,400);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
//painter.drawEllipse(rectangle);
QPen pen;
pen.setStyle(Qt::SolidLine);
pen.setColor(QColor("Black"));
pen.setWidth(5);
painter.setPen(pen);
painter.translate(this->width()/2,this->height()/2);
painter.drawEllipse(QPoint(0,0),250,250);
int i=12;
while(i--)
{
painter.rotate(30);
painter.drawLine(0,220,0,250);
}
int j=60;
while(j--)
{
painter.rotate(6);
painter.drawLine(0,240,0,250);
}
painter.rotate(180);
painter.save();
pen.setWidth(8);
pen.setColor(QColor("red"));
painter.setPen(pen);
painter.rotate(30*hour+0.5*minute+0.5/60*second);
painter.drawLine(0,0,0,50);
painter.restore();
painter.save();
pen.setWidth(5);
pen.setColor(QColor("blue"));
painter.setPen(pen);
painter.rotate(6*minute+0.1*second);
painter.drawLine(0,0,0,90);
painter.restore();
painter.save();
pen.setWidth(1);
pen.setColor(QColor("green"));
painter.setPen(pen);
painter.rotate(6*second);
painter.drawLine(0,0,0,150);
painter.restore();
}
void Widget::timer_slot()
{
/*
this->label->resize(200,100);
this->label->move(this->width()-100,this->height()+150);
*/
QTime sys_t = QTime::currentTime(); //获得系统时间
this->hour=sys_t.hour();
this->minute=sys_t.minute();
this->second=sys_t.second();
update();
/*
//将QTime类对象转换为字符串
QString t1 = sys_t.toString("hh:mm:ss");
//展示
this->label->setText(t1);
*/
}
main.cpp:
cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}