Qt自定义控件8:根据背景图片画时钟

Qt自定义控件8:根据背景图片画时钟

先看效果图:
Qt自定义控件8:根据背景图片画时钟_第1张图片

基础背景图:
Qt自定义控件8:根据背景图片画时钟_第2张图片

思路:将背景图片绘制上,在背景图片上画刻度线,刻度值,和三个指针。定义定时器,刷新时间

关键代码:CMProgressBar3.cpp

void CMProgressBar3::paintEvent(QPaintEvent *event){
    int width = this->width();
    int height = this->height();
    int side = qMin(width, height);

    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.translate(width / 2, height / 2);
    painter.scale(side / 200.0, side / 200.0);

    drawBgMap(&painter);
    drawLines(&painter);
    drawText(&painter);
    drawPoint(&painter);
}

void CMProgressBar3::drawBgMap(QPainter* painter){
    painter->save();
    QString path = ":/image/images/bg.png";
    QImage image(path);
    QRect rect(-radius,-radius,radius*2,radius*2);
    painter->drawImage(rect,image);
    painter->restore();
}

void CMProgressBar3::drawLines(QPainter* painter){
     painter->save();
     painter->setPen(QPen(Qt::black));
     //时针刻度
     int rangeH = 360/12;
     for(int i = 0;i<12;i++){
         painter->rotate(rangeH);
         painter->drawLine(QPoint(radius-hLineLength,0),QPoint(radius-1,0));
     }
     painter->restore();

     //分针刻度
     painter->save();
     painter->setPen(QPen(Qt::black));
     int rangeM = 360/60;
     for(int i = 0;i<60;i++){
         painter->rotate(rangeM);
         painter->drawLine(QPoint(radius-mLineLength,0),QPoint(radius-1,0));
     }
     painter->restore();

}

void CMProgressBar3::drawText(QPainter *painter){
    //刻度
    painter->save();
    painter->setPen(QPen(Qt::white));
    for(int i = 1;i<=12;i++){

        QRect rect(-55*qSin(30*(i+6)*3.14/180)-5,55*qCos(30*(i+6)*3.14/180),10,5);
        QFont font = painter->font();
        font.setPixelSize(7);
        painter->setFont(font);
        painter->drawText(rect,Qt::AlignCenter,QString::number(i));
    }
    painter->restore();
}

void CMProgressBar3::drawPoint(QPainter *painter){

    QPoint secHand[4] = {
        QPoint(0,0),
        QPoint(2,-2),
        QPoint(0,-50),
        QPoint(-2,-2)
        };
    QPoint minHand[4] = {
        QPoint(0,0),
        QPoint(2,-3.5),
        QPoint(0,-40),
        QPoint(-2,-3.5)
        };
    QPoint hourHand[4] = {
        QPoint(0,0),
        QPoint(2,-5),
        QPoint(0,-25),
        QPoint(-2,-5)
        };
    QTime curTime = QTime::currentTime();
    painter->save();
    painter->setBrush(QBrush(QColor("#1A74A7")));
    painter->rotate(curTime.hour()*30+curTime.minute()/60);
    painter->drawConvexPolygon(hourHand,4);
    painter->restore();

    painter->save();
    painter->setBrush(QBrush(QColor("#1C6869")));
    painter->rotate(curTime.minute()*6);
    painter->drawConvexPolygon(minHand,4);
    painter->restore();

    painter->save();
    painter->setBrush(QBrush(QColor("#AB5C10")));
    painter->rotate(curTime.second()*6);
    painter->drawConvexPolygon(secHand,4);
    painter->restore();
}

你可能感兴趣的:(Qt画图(自定义控件))