使用Qt绘画事件处理画一个闹钟
头文件
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QTime>
#include <QTimer>
#include <QTimerEvent>
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;
public slots:
void timeout_slot();
private:
Ui::Widget *ui;
QTimer t1;
int tid=0;
int hou1;//小时
int min1;//分
int sec1;//秒
};
#endif // WIDGET_H
源文件
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
t1.start(1000);
//timeout信号与槽函数链接
connect(&t1,&QTimer::timeout,this,&Widget::timeout_slot);
}
Widget::~Widget()
{
delete ui;
}
//槽函数
void Widget::timeout_slot()
{
update();
// QPaintEvent *Q=nullptr;
// this->paintEvent(Q);
}
//绘制事件处理函数
void Widget::paintEvent(QPaintEvent *event)
{
QTime sysTime=QTime::currentTime();
QString t=sysTime.toString("hh:mm:ss");//转换为字符串
QStringList tlist =t.split(":"); //以 :分割t
hou1 =tlist[0].toUInt(); //将小时传化为无符号整数
min1 =tlist[1].toUInt(); //将分钟传化为无符号整数
sec1 =tlist[2].toUInt(); //将秒传化为无符号整数
QPainter painter(this);//实例一个画家
//准备画笔
QPen pen;
pen.setStyle(Qt::SolidLine);
pen.setColor(QColor("purple"));
pen.setWidth(5);
//字体
QFont font;
font.setFamily("楷体");
font.setPointSize(10);
//给画家
painter.setPen(pen);
painter.translate(this->width()/2,this->height()/2);//设置画家起点
painter.drawEllipse(QPoint(0,0),250,250);//绘制一个圆
pen.setColor(QColor("black"));
painter.setPen(pen);
//画刻度
for(int i=1;i<=60;i++)
{
painter.rotate(6);
if(i%5!=0)
{
pen.setWidth(3);
painter.setPen(pen);
painter.drawLine(0,242,0,250);
}
else
{
pen.setWidth(6);
painter.setPen(pen);
painter.drawLine(0,235,0,250);
painter.drawText(QRect(-10,-220,20,20),Qt::AlignCenter,QString::number(i/5));
}
}
//时针
painter.save();
pen.setColor(QColor("red"));
pen.setWidth(15);
painter.setPen(pen);
painter.rotate(hou1*30+(min1/60)*6+sec1/10);
painter.drawLine(0,-5,0,-80);
painter.restore();
//分钟
painter.save();
pen.setColor(QColor("blue"));
pen.setWidth(10);
painter.setPen(pen);
painter.rotate(min1*6+sec1/60*6);
painter.drawLine(0,-5,0,-120);
painter.restore();
//秒针
painter.save();
pen.setColor(QColor("yellow"));
pen.setWidth(5);
painter.setPen(pen);
painter.rotate(sec1*6);
painter.drawLine(0,-5,0,-180);
painter.restore();
}