制作一个简易圆形时钟
头文件:
- #ifndef WIDGET_H
- #define WIDGET_H
-
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- QT_BEGIN_NAMESPACE
- namespace Ui { class Widget; }
- QT_END_NAMESPACE
-
- class Widget : public QWidget
- {
- Q_OBJECT
-
- public:
- Widget(QWidget *parent = nullptr);
- ~Widget();
- void timerEvent(QTimerEvent *e)override;
- void paintEvent(QPaintEvent *event) override;
-
- private:
- Ui::Widget *ui;
- int timer_id;
-
- };
- #endif // WIDGET_H
源文件:
- #include "widget.h"
- #include "ui_widget.h"
-
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::Widget)
- {
- ui->setupUi(this);
- }
-
- Widget::~Widget()
- {
- delete ui;
- }
-
- void Widget::paintEvent(QPaintEvent *event)
- {
- QPainter painter(this);//创建一个画师对象
- painter.setRenderHint(QPainter::Antialiasing);
-
- // 将原点移动到窗口中心 (使画布居中)
- painter.translate(width() / 2, height() / 2);
-
- //放大
- painter.scale(2, 2);
-
- // 绘制表盘
- painter.setPen(Qt::black);//设置画笔为空。
- painter.setBrush(Qt::white);//设置画刷为白色。
- painter.drawEllipse(-100,-100, 200, 200);
- painter.drawText(-7,-78,"12");
- painter.drawText(78,5,"3");
- painter.drawText(-5,85,"6");
- painter.drawText(-83,5,"9");
- // 绘制刻度
- painter.setPen(Qt::black);//设置画笔为黑色。
- for (int i = 0; i < 12; ++i) {//循环绘制时钟刻度
- painter.drawLine(0, -90, 0, -100);
- painter.rotate(30);
- }
- for (int i = 0; i < 36; ++i) {
- painter.drawLine(0, -95, 0, -100);
- painter.rotate(10);
- }
-
- // 绘制时针、分针和秒针
- QTime time = QTime::currentTime();//获取当前时间。
- painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
- painter.setPen(Qt::NoPen);
- painter.setBrush(Qt::black);
- // 绘制时针,以多边形方式绘制,坐标点依次为(-2,5)、(2,5)、(0,-80)
- painter.drawPolygon(QPolygonF(QVector
() << QPointF(-2, 5) - << QPointF(2, 5)
- << QPointF(0, -50)));
-
- painter.rotate(6.0 * (time.minute() + time.second() / 60.0));//60分钟转360度,一分钟转6度
- painter.setBrush(Qt::blue);
- painter.drawPolygon(QPolygonF(QVector
() << QPointF(-1, 5) - << QPointF(1, 5)
- << QPointF(0, -75)));
-
- painter.rotate(6.0 * time.second());
- painter.setBrush(Qt::red);
- painter.drawPolygon(QPolygonF(QVector
() << QPointF(-1, 5) - << QPointF(1, 5)
- << QPointF(0, -90)));
-
- this->update();
- }
-
- void Widget::timerEvent(QTimerEvent *e)
- {
- timer_id=this->startTimer(1000);
- }
-
-
测试文件:
- #include "widget.h"
-
- #include
-
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Widget w;
- w.show();
- return a.exec();
- }
运行结果:
思维导图: