通过QT实现简单的钟表
效果如图
设计方法
首先准备好钟表样式图片,ps扣除其中指针表盘等。
建立dialog类项目。
将dialog重置大小,插入图片
在Dialog类内声明paintEvent和timerEvent(纯虚函数的利用),并在cpp中进行定义。
在paintEvent中利用QPainter类进行绘制:
首先是表盘,首先将表中心设置为新的坐标原点(translate()函数),之后利用旋转(rotate()函数)和绘针函数(fillrect()函数),每次绘针需要保存并复原坐标系(save()函数和restore()函数);
在timerevent中实现对paintEvent的重复调用(repaint()函数);
具体代码如下:
代码
header.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
void paintEvent(QPaintEvent * event);
void timerEvent(QTimerEvent *event);
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include<QPainter>
#include<QPixmap>
#include<QWindow>
#include<QTime>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
resize(500,375);
startTimer(1000);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent *event){
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QPixmap map(":/new/prefix1/cccc.jpg");
QRect q1(0,0,500,375);
QRect q2(0,0,width(),height());
painter.drawPixmap(q2,map,q1);
painter.translate(179,210);
painter.drawEllipse(QPoint(0,0),3,3);
//长表盘
for(int i=0;i<12;i++){
painter.save();
painter.rotate(30*i);
painter.drawLine(0,100,0,95);
painter.restore();
};
//短表盘
for(int i=0;i<60;i++){
if(i%5){
painter.save();
painter.rotate(6*i);
painter.drawPoint(0,100);
painter.restore();
}
}
//获取系统时间
QTime time=QTime::currentTime();
//绘制秒针
painter.save();
painter.rotate(6.0*time.second()-180);
painter.fillRect(-2,-10,4,100,Qt::gray);
painter.restore();
//绘制分针
painter.save();
painter.rotate(6.0*(time.minute()+time.second()/60.0)-180);
painter.fillRect(-3,-6,6,60,Qt::gray);
painter.restore();
//绘制时针
painter.save();
painter.rotate(30.0*(time.hour()+time.minute()/60.0+time.second()/3600.0)-180);
painter.fillRect(-4,-4,8,40,Qt::gray);
painter.restore();
}
void Dialog::timerEvent(QTimerEvent * event){
repaint();
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}